diff --git a/symbolicai-main/symbolicai-main/.gitbook.yaml b/symbolicai-main/symbolicai-main/.gitbook.yaml deleted file mode 100644 index b591b5208e97744512725a5dd8cd50651c7bbe90..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/.gitbook.yaml +++ /dev/null @@ -1,5 +0,0 @@ -root: symbolicai/docs/source/ - -structure: - readme: INTRODUCTION.md - summary: SUMMARY.md diff --git a/symbolicai-main/symbolicai-main/.github/FUNDING.yml b/symbolicai-main/symbolicai-main/.github/FUNDING.yml deleted file mode 100644 index 3efd81fdb00cbed499bb300bc1ce24e1641cdeea..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/.github/FUNDING.yml +++ /dev/null @@ -1,13 +0,0 @@ -# These are supported funding model platforms - -github: [extensityAI] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry -custom: ['https://www.paypal.com/donate/?hosted_button_id=WCWP5D2QWZXFQ'] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/symbolicai-main/symbolicai-main/.gitignore b/symbolicai-main/symbolicai-main/.gitignore deleted file mode 100644 index d3bbbad9d5ae62d2132f6b73ca58766fd0ae9ac2..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/.gitignore +++ /dev/null @@ -1,163 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -docs/_build/ -docs/.doctrees/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -pip-wheel-metadata/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py,cover -.hypothesis/ -.pytest_cache/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -.python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# SageMath parsed files -*.sage.py - -# Environments -.env -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -results/ -symai.config.json -.DS_Store -._.DS_Store -**/.DS_Store -**/._.DS_Store - - -# ignore all files in the symai/extended/packages/ directory -notebooks/demos/**/* -.virtual_documents/notebooks -notebooks/.virtual_documents -outputs/ -demos/ -wandb/ -tmp/ -dist/ -bin/ -.idea -scripts -SymbolicAI_Installer_**.* -entitlements.plist -favicon.ico -icon.ico -icon.icns -release_**/* -packages/ExtensityAI/LightRAG-symai -sympkg -symsh -.bash_history -.conversation_state diff --git a/symbolicai-main/symbolicai-main/.symai/symsh.config.json b/symbolicai-main/symbolicai-main/.symai/symsh.config.json deleted file mode 100644 index 83759621706925dbc144d8b9f962fbdee1b93f9d..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/.symai/symsh.config.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "colors": { - "completion-menu.completion.current": "bg:#323232 #212121", - "completion-menu.completion": "bg:#800080 #212121", - "scrollbar.background": "bg:#222222", - "scrollbar.button": "bg:#776677", - "history-completion": "bg:#212121 #f5f5f5", - "path-completion": "bg:#800080 #f5f5f5", - "file-completion": "bg:#9040b2 #f5f5f5", - "history-completion-selected": "bg:#efefef #b3d7ff", - "path-completion-selected": "bg:#efefef #b3d7ff", - "file-completion-selected": "bg:#efefef #b3d7ff" - }, - "map-nt-cmd": true, - "show-splash-screen": true -} \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/CITATION.cff b/symbolicai-main/symbolicai-main/CITATION.cff deleted file mode 100644 index 32770ed85cb2db0f91a6f0bc904df1043aebf1cd..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/CITATION.cff +++ /dev/null @@ -1,12 +0,0 @@ -cff-version: 1.2.0 -message: "If you use this software, please cite it as below." -authors: -- family-names: "Dinu" - given-names: "Marius-Constantin" - orcid: "https://orcid.org/my-orcid?orcid=0000-0002-7518-3337" -editors: -- family-names: "Leoveanu-Condrei" - given-names: "Claudiu" -title: "SymbolicAI: A Neuro-Symbolic Perspective on Large Language Models (LLMs)" -date-released: 2022-11-30 -url: "https://github.com/Xpitfire/symbolicai" diff --git a/symbolicai-main/symbolicai-main/Dockerfile b/symbolicai-main/symbolicai-main/Dockerfile deleted file mode 100644 index 6f667f1a3fb9918da476a4f0b5498e58411dbdc7..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/Dockerfile +++ /dev/null @@ -1,49 +0,0 @@ -# syntax=docker/dockerfile:1 -FROM pytorch/pytorch:2.0.1-cuda11.7-cudnn8-devel - -LABEL symai.image.authors="extensity.ai" \ - symai.image.vendor="ExtensityAI" \ - symai.image.title="SymbolicAI" \ - symai.image.description="SymbolicAI: Compositional Differentiable Programming Library" \ - symai.image.source="https://github.com/ExtensityAI/symbolicai.git" \ - symai.image.revision="${VCS_REF}" \ - symai.image.created="${BUILD_DATE}" \ - symai.image.documentation="https://symbolicai.readthedocs.io/en/latest/README.html" -LABEL symai.dependencies.versions.torch="2.0.1" -LABEL symai.dependencies.versions.cuda="11.7" -ARG DEBIAN_FRONTEND=noninteractive - -# NVIDIA key migration -RUN apt-key del 7fa2af80 -RUN apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/3bf863cc.pub -RUN apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu2004/x86_64/7fa2af80.pub -# Update the base image -RUN apt update && apt upgrade -y - -# Install symai - -## Install dependencies -RUN apt install -y curl sudo nano git htop netcat wget unzip tmux apt-utils cmake build-essential libgl1-mesa-glx libglib2.0-0 - -## Upgrade pip -RUN pip3 install --upgrade pip - -# Install nvm and pm2 -RUN curl -o install_nvm.sh https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh && \ - echo 'fabc489b39a5e9c999c7cab4d281cdbbcbad10ec2f8b9a7f7144ad701b6bfdc7 install_nvm.sh' | sha256sum --check && \ - bash install_nvm.sh - -RUN bash -c "source $HOME/.nvm/nvm.sh && \ - # use node 16 - nvm install 16 && \ - # install pm2 - npm install --location=global pm2" - -RUN mkdir -p /root/.symai/install -COPY . /root/.symai/install -RUN cd /root/.symai/install && python3 -m pip install ".[all]" - -# Increase ulimit to 1,000,000 -RUN prlimit --pid=$PPID --nofile=1000000 - -EXPOSE 8999 diff --git a/symbolicai-main/symbolicai-main/MANIFEST.in b/symbolicai-main/symbolicai-main/MANIFEST.in deleted file mode 100644 index d78ef472486146943c19b054fc9bc3c7a7addc59..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/MANIFEST.in +++ /dev/null @@ -1,4 +0,0 @@ -global-exclude test_*.py -include symai/**/* -include symai/backend/driver/* -exclude **/*.pyc \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/README.md b/symbolicai-main/symbolicai-main/README.md deleted file mode 100644 index b6e2905b87c11790aa2d623089d7eb4eaa7d0057..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/README.md +++ /dev/null @@ -1,371 +0,0 @@ -# **SymbolicAI: A neuro-symbolic perspective on LLMs** - - -
- -[![Documentation](https://img.shields.io/badge/Documentation-blue?style=for-the-badge)](https://extensityai.gitbook.io/symbolicai) -[![Arxiv](https://img.shields.io/badge/Paper-32758e?style=for-the-badge)](https://arxiv.org/abs/2402.00854) -[![DeepWiki](https://img.shields.io/badge/DeepWiki-yellow?style=for-the-badge)](https://deepwiki.com/ExtensityAI/symbolicai) - -[![Twitter](https://img.shields.io/twitter/url/https/twitter.com/dinumariusc.svg?style=social&label=@DinuMariusC)](https://twitter.com/DinuMariusC) [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/symbolicapi.svg?style=social&label=@ExtensityAI)](https://twitter.com/ExtensityAI) -[![Twitter](https://img.shields.io/twitter/url/https/twitter.com/futurisold.svg?style=social&label=@futurisold)](https://x.com/futurisold) - -
- ---- - - - -## What is SymbolicAI? - -SymbolicAI is a **neuro-symbolic** framework, combining classical Python programming with the differentiable, programmable nature of LLMs in a way that actually feels natural in Python. -It's built to not stand in the way of your ambitions. -It's easily extensible and customizable to your needs by virtue of its modular design. -It's quite easy to [write your own engine](https://extensityai.gitbook.io/symbolicai/engines/custom_engine), [host locally](https://extensityai.gitbook.io/symbolicai/engines/local_engine) an engine of your choice, or interface with tools like [web search](https://extensityai.gitbook.io/symbolicai/engines/search_engine) or [image generation](https://extensityai.gitbook.io/symbolicai/engines/drawing_engine). -To keep things concise in this README, we'll introduce two key concepts that define SymbolicAI: **primitives** and **contracts**. - -### Primitives -At the core of SymbolicAI are `Symbol` objects—each one comes with a set of tiny, composable operations that feel like native Python. -```python -from symai import Symbol -``` - -`Symbol` comes in **two flavours**: - -1. **Syntactic** – behaves like a normal Python value (string, list, int ‐ whatever you passed in). -2. **Semantic** – is wired to the neuro-symbolic engine and therefore *understands* meaning and - context. - -Why is syntactic the default? -Because Python operators (`==`, `~`, `&`, …) are overloaded in `symai`. -If we would immediately fire the engine for *every* bitshift or comparison, code would be slow and could produce surprising side-effects. -Starting syntactic keeps things safe and fast; you opt-in to semantics only where you need them. - -#### How to switch to the semantic view - -1. **At creation time** - - ```python - S = Symbol("Cats are adorable", semantic=True) # already semantic - print("feline" in S) # => True - ``` - -2. **On demand with the `.sem` projection** – the twin `.syn` flips you back: - - ```python - S = Symbol("Cats are adorable") # default = syntactic - print("feline" in S.sem) # => True - print("feline" in S) # => False - ``` - -3. Invoking **dot-notation operations**—such as `.map()` or any other semantic function—automatically switches the symbol to semantic mode: - - ```python - S = Symbol(['apple', 'banana', 'cherry', 'cat', 'dog']) - print(S.map('convert all fruits to vegetables')) - # => ['carrot', 'broccoli', 'spinach', 'cat', 'dog'] - ``` - -Because the projections return the *same underlying object* with just a different behavioural coat, you can weave complex chains of syntactic and semantic operations on a single symbol. Think of them as your building blocks for semantic reasoning. Right now, we support a wide range of primitives; check out the docs [here](https://extensityai.gitbook.io/symbolicai/features/primitives), but here's a quick snack: - -| Primitive/Operator | Category | Syntactic | Semantic | Description | -|--------------------|-----------------|:---------:|:--------:|-------------| -| `==` | Comparison | ✓ | ✓ | Tests for equality. Syntactic: literal match. Semantic: fuzzy/conceptual equivalence (e.g. 'Hi' == 'Hello'). | -| `+` | Arithmetic | ✓ | ✓ | Syntactic: numeric/string/list addition. Semantic: meaningful composition, blending, or conceptual merge. | -| `&` | Logical/Bitwise | ✓ | ✓ | Syntactic: bitwise/logical AND. Semantic: logical conjunction, inference, e.g., context merge. | -| `symbol[index] = value` | Iteration | ✓ | ✓ | Set item or slice. | -| `.startswith(prefix)` | String Helper | ✓ | ✓ | Check if a string starts with given prefix (in both modes). | -| `.choice(cases, default)` | Pattern Matching| | ✓ | Select best match from provided cases. | -| `.foreach(condition, apply)`| Execution Control | | ✓ | Apply action to each element. | -| `.cluster(**clustering_kwargs?)` | Data Clustering | | ✓ | Cluster data into groups semantically. (uses sklearn's DBSCAN)| -| `.similarity(other, metric?, normalize?)` | Embedding | | ✓ | Compute similarity between embeddings. | -| ... | ... | ...| ... | ... | - -### Contracts - -They say LLMs hallucinate—but your code can't afford to. That's why SymbolicAI brings **Design by Contract** principles into the world of LLMs. Instead of relying solely on post-hoc testing, contracts help build correctness directly into your design, everything packed into a decorator that will operate on your defined data models and validation constraints: -```python -from symai import Expression -from symai.strategy import contract -from symai.models import LLMDataModel # Compatible with Pydantic's BaseModel -from pydantic import Field, field_validator - -# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ -# Data models ▬ -# – clear structure + rich Field descriptions power ▬ -# validation, automatic prompt templating & remedies ▬ -# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ -class DataModel(LLMDataModel): - some_field: some_type = Field(description="very descriptive field", and_other_supported_options_here="...") - - @field_validator('some_field') - def validate_some_field(cls, v): - # Custom basic validation logic can be added here too besides pre/post - valid_opts = ['A', 'B', 'C'] - if v not in valid_opts: - raise ValueError(f'Must be one of {valid_opts}, got "{v}".') - return v - -# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ -# The contracted expression class ▬ -# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ -@contract( - # ── Remedies ─────────────────────────────────────────── # - pre_remedy=True, # Try to fix bad inputs automatically - post_remedy=True, # Try to fix bad LLM outputs automatically - accumulate_errors=True, # Feed history of errors to each retry - verbose=True, # Nicely displays progress in terminal - remedy_retry_params=dict(tries=3, delay=0.4, max_delay=4.0, - jitter=0.15, backoff=1.8, graceful=False), -) -class Agent(Expression): - # - # High-level behaviour: - # *. `prompt` – a *static* description of what the LLM must do (mandatory) - # 1. `pre` – sanity-check inputs (optional) - # 2. `act` – mutate state (optional) - # 3. LLM – generate expected answer (handled by SymbolicAI engine) - # 4. `post` – ensure answer meets semantic rules (optional) - # 5. `forward` (mandatory) - # • if contract succeeded → return type validated LLM object - # • else → graceful fallback answer - # ... -``` - -Because we don't want to bloat this README file with long Python snippets, learn more about contracts [here](https://deepwiki.com/ExtensityAI/symbolicai/7.1-contract-validation-system) and [here](https://extensityai.gitbook.io/symbolicai/features/contracts). - -## Installation - -### Core Features - -To get started with SymbolicAI, you can install it using pip: - -```bash -pip install symbolicai -``` - -#### Setting up a neurosymbolic API Key - -Before using SymbolicAI, you need to set up API keys for the various engines. Currently, SymbolicAI supports the following neurosymbolic engines through API: OpenAI, Anthropic. We also support {doc}`local neurosymbolic engines `, such as llama.cpp and huggingface. - -```bash -# Linux / MacOS -export NEUROSYMBOLIC_ENGINE_API_KEY="…" -export NEUROSYMBOLIC_ENGINE_MODEL="…" -``` - -```bash -# Windows (PowerShell) -$Env:NEUROSYMBOLIC_ENGINE_API_KEY="…" -$Env:NEUROSYMBOLIC_ENGINE_MODEL="…" -``` - -```bash -# Jupyter Notebooks -%env NEUROSYMBOLIC_ENGINE_API_KEY=… -%env NEUROSYMBOLIC_ENGINE_MODEL=… -``` - -#### Optional Features - -SymbolicAI uses multiple engines to process text, speech and images. We also include search engine access to retrieve information from the web. To use all of them, you will need to also install the following dependencies and assign the API keys to the respective engines. - -```bash -pip install "symbolicai[wolframalpha]" -pip install "symbolicai[whisper]" -pip install "symbolicai[selenium]" -pip install "symbolicai[serpapi]" -pip install "symbolicai[pinecone]" -``` - -Or, install all optional dependencies at once: - -```bash -pip install "symbolicai[all]" -``` - -And export the API keys, for example: - -```bash -# Linux / MacOS -export SYMBOLIC_ENGINE_API_KEY="" -export SEARCH_ENGINE_API_KEY="" -export OCR_ENGINE_API_KEY="" -export INDEXING_ENGINE_API_KEY="" - -# Windows (PowerShell) -$Env:SYMBOLIC_ENGINE_API_KEY="" -$Env:SEARCH_ENGINE_API_KEY="" -$Env:OCR_ENGINE_API_KEY="" -$Env:INDEXING_ENGINE_API_KEY="" -``` - -See below for the entire list of keys that can be set via environment variables or a configuration file. - -#### Additional Requirements - -**SpeechToText Engine**: Install `ffmpeg` for audio processing (based on OpenAI's [whisper](https://openai.com/blog/whisper/)) - -```bash -# Linux -sudo apt update && sudo apt install ffmpeg - -# MacOS -brew install ffmpeg - -# Windows -choco install ffmpeg -``` - -**WebCrawler Engine**: For `selenium`, we automatically install the driver with `chromedriver-autoinstaller`. Currently we only support Chrome as the default browser. - -## Configuration Management - -SymbolicAI now features a configuration management system with priority-based loading. The configuration system looks for settings in three different locations, in order of priority: - -1. **Debug Mode** (Current Working Directory) - - Highest priority - - Only applies to `symai.config.json` - - Useful for development and testing - -2. **Environment-Specific Config** (Python Environment) - - Second priority - - Located in `{python_env}/.symai/` - - Ideal for project-specific settings - -3. **Global Config** (Home Directory) - - Lowest priority - - Located in `~/.symai/` - - Default fallback for all settings - -### Configuration Files - -The system manages three main configuration files: -- `symai.config.json`: Main SymbolicAI configuration -- `symsh.config.json`: Shell configuration -- `symserver.config.json`: Server configuration - -### Viewing Your Configuration - -Before using the package, we recommend inspecting your current configuration setup using the command below. This will create all the necessary configuration files. - -```bash -symconfig -``` - -This command will show: -- All configuration locations -- Active configuration paths -- Current settings (with sensitive data truncated) - -### Configuration Priority Example - -```console -my_project/ # Debug mode (highest priority) -└── symai.config.json # Only this file is checked in debug mode - -{python_env}/.symai/ # Environment config (second priority) -├── symai.config.json -├── symsh.config.json -└── symserver.config.json - -~/.symai/ # Global config (lowest priority) -├── symai.config.json -├── symsh.config.json -└── symserver.config.json -``` - -If a configuration file exists in multiple locations, the system will use the highest-priority version. If the environment-specific configuration is missing or invalid, the system will automatically fall back to the global configuration in the home directory. - -### Best Practices - -- Use the global config (`~/.symai/`) for your default settings -- Use environment-specific configs for project-specific settings -- Use debug mode (current directory) for development and testing -- Run `symconfig` to inspect your current configuration setup - -This addition to the README clearly explains: -1. The priority-based configuration system -2. The different configuration locations and their purposes -3. How to view and manage configurations -4. Best practices for configuration management - -### Configuration File - -You can specify engine properties in a `symai.config.json` file in your project path. This will replace the environment variables. -Example of a configuration file with all engines enabled: -```json -{ - "NEUROSYMBOLIC_ENGINE_API_KEY": "", - "NEUROSYMBOLIC_ENGINE_MODEL": "gpt-4o", - "SYMBOLIC_ENGINE_API_KEY": "", - "SYMBOLIC_ENGINE": "wolframalpha", - "EMBEDDING_ENGINE_API_KEY": "", - "EMBEDDING_ENGINE_MODEL": "text-embedding-3-small", - "SEARCH_ENGINE_API_KEY": "", - "SEARCH_ENGINE_MODEL": "sonar", - "TEXT_TO_SPEECH_ENGINE_API_KEY": "", - "TEXT_TO_SPEECH_ENGINE_MODEL": "tts-1", - "INDEXING_ENGINE_API_KEY": "", - "INDEXING_ENGINE_ENVIRONMENT": "us-west1-gcp", - "DRAWING_ENGINE_API_KEY": "", - "DRAWING_ENGINE_MODEL": "dall-e-3", - "VISION_ENGINE_MODEL": "openai/clip-vit-base-patch32", - "OCR_ENGINE_API_KEY": "", - "SPEECH_TO_TEXT_ENGINE_MODEL": "turbo", - "SUPPORT_COMMUNITY": true -} -``` - -With these steps completed, you should be ready to start using SymbolicAI in your projects. - -> ❗️**NOTE**❗️Our framework allows you to support us train models for local usage by enabling the data collection feature. On application startup we show the terms of services and you can activate or disable this community feature. We do not share or sell your data to 3rd parties and only use the data for research purposes and to improve your user experience. To change this setting open the `symai.config.json` and turn it on/off by setting the `SUPPORT_COMMUNITY` property to `True/False` via the config file or the respective environment variable. - -> ❗️**NOTE**❗️By default, the user warnings are enabled. To disable them, export `SYMAI_WARNINGS=0` in your environment variables. - -### Running tests -Some examples of running tests locally: -```bash -# Run all tests -pytest tests -# Run mandatory tests -pytest -m mandatory -``` -Be sure to have your configuration set up correctly before running the tests. You can also run the tests with coverage to see how much of the code is covered by tests: -```bash -pytest --cov=symbolicai tests -``` - -## 🪜 Next Steps - -Now, there are tools like DeepWiki that provide better documentation than we could ever write, and we don’t want to compete with that; we'll correct it where it's plain wrong. Please go read SymbolicAI's DeepWiki [page](https://deepwiki.com/ExtensityAI/symbolicai/). There's a lot of interesting stuff in there. Last but not least, check out our [paper](https://arxiv.org/abs/2402.00854) that describes the framework in detail. If you like watching videos, we have a series of tutorials that you can find [here](https://extensityai.gitbook.io/symbolicai/tutorials/video_tutorials). - -## 📜 Citation - -```bibtex -@software{Dinu_SymbolicAI_2022, - author = {Dinu, Marius-Constantin}, - editor = {Leoveanu-Condrei, Claudiu}, - title = {{SymbolicAI: A Neuro-Symbolic Perspective on Large Language Models (LLMs)}}, - url = {https://github.com/ExtensityAI/symbolicai}, - month = {11}, - year = {2022} -} -``` - -## 📝 License - -This project is licensed under the BSD-3-Clause License - refer to [the docs](https://symbolicai.readthedocs.io/en/latest/LICENSE.html). - -## Like this Project? - -If you appreciate this project, please leave a star ⭐️ and share it with friends and colleagues. To support the ongoing development of this project even further, consider donating. Thank you! - -[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg?style=for-the-badge)](https://www.paypal.com/donate/?hosted_button_id=WCWP5D2QWZXFQ) - -We are also seeking contributors or investors to help grow and support this project. If you are interested, please reach out to us. - -## 📫 Contact - -Feel free to contact us with any questions about this project via [email](mailto:office@extensity.ai), through our [website](https://extensity.ai/), or find us on Discord: -[![Discord](https://img.shields.io/discord/768087161878085643?label=Discord&logo=Discord&logoColor=white?style=for-the-badge)](https://discord.gg/QYMNnh9ra8) diff --git a/symbolicai-main/symbolicai-main/app.py b/symbolicai-main/symbolicai-main/app.py deleted file mode 100644 index 958785f389193b09468de9095e149e1b294155d4..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/app.py +++ /dev/null @@ -1,3 +0,0 @@ -from symai import shell - -shell.run() diff --git a/symbolicai-main/symbolicai-main/assets/images/banner.png b/symbolicai-main/symbolicai-main/assets/images/banner.png deleted file mode 100644 index 07c1de3e2d2155c996d8a554782a951072b1009d..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/assets/images/banner.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ee5a5aed1b6adeb3fcaf3d52abb3e3d1881c4cff673f3f7ac2b146930ee6ed72 -size 417639 diff --git a/symbolicai-main/symbolicai-main/assets/images/cat.jpg b/symbolicai-main/symbolicai-main/assets/images/cat.jpg deleted file mode 100644 index 1b058fd2012c60464b8ffaf2f519feca42ead521..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/cat.jpg and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/cat.png b/symbolicai-main/symbolicai-main/assets/images/cat.png deleted file mode 100644 index a53b75eb3d1f2f1bd9189d5bae8d12ef4185d3b7..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/assets/images/cat.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:875577457a09e3d84f6b7ce4745b775147f93990fd0b216664f0dab6b56e453c -size 1303401 diff --git a/symbolicai-main/symbolicai-main/assets/images/img1.png b/symbolicai-main/symbolicai-main/assets/images/img1.png deleted file mode 100644 index c7319fb0337f9872a43dc7031c22a326ba8b556e..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/img1.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/img10.png b/symbolicai-main/symbolicai-main/assets/images/img10.png deleted file mode 100644 index f21ecf25ee679ce5fe613811da4483152023dcb6..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/img10.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/img2.png b/symbolicai-main/symbolicai-main/assets/images/img2.png deleted file mode 100644 index b874c9dd6ea7e84e43a7bd87ad1e274296860cab..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/img2.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/img3.png b/symbolicai-main/symbolicai-main/assets/images/img3.png deleted file mode 100644 index 6e5e0053c975028d19425669c43eac4f900ec9d4..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/img3.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/img4.png b/symbolicai-main/symbolicai-main/assets/images/img4.png deleted file mode 100644 index ffddd6d416a9b0c19ac49905c3507bf203af4a2f..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/img4.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/img5.png b/symbolicai-main/symbolicai-main/assets/images/img5.png deleted file mode 100644 index 11a0c1c83a09f08ea3a37d729a4798fca3014910..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/img5.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/img6.png b/symbolicai-main/symbolicai-main/assets/images/img6.png deleted file mode 100644 index 4162226b4cfa24a642ee8a776349db0c989ba713..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/img6.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/img7.png b/symbolicai-main/symbolicai-main/assets/images/img7.png deleted file mode 100644 index 92e9326b05447b8c01546de47adf9afc8569a220..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/img7.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/img8.png b/symbolicai-main/symbolicai-main/assets/images/img8.png deleted file mode 100644 index 4d2bf0a80c71702f3df0830b64fec8c75e01a2b6..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/assets/images/img8.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:911781724545945be5562e420326ce2307e648541f990a1226cabecfe736f683 -size 211609 diff --git a/symbolicai-main/symbolicai-main/assets/images/img9.png b/symbolicai-main/symbolicai-main/assets/images/img9.png deleted file mode 100644 index 6d781e9a6f31ee1aedb90ae67052cb820ea8a48e..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/img9.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/preview.gif b/symbolicai-main/symbolicai-main/assets/images/preview.gif deleted file mode 100644 index 2d091a3309309d2020a5fe09b196941e522f3e43..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/assets/images/preview.gif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:59582115271fdfe7d08c2931da24ca332d30d4cc70e9678312e899fc1f9ac652 -size 1277783 diff --git a/symbolicai-main/symbolicai-main/assets/images/screen1.jpeg b/symbolicai-main/symbolicai-main/assets/images/screen1.jpeg deleted file mode 100644 index c94838d8c1220a29c0c89ee379675a41ff591dbf..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/assets/images/screen1.jpeg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:97afae65e439aaac9a96e1a02d1f61b19f6611169f0bc7276c8de6148f357a6e -size 451461 diff --git a/symbolicai-main/symbolicai-main/assets/images/symai_logo.png b/symbolicai-main/symbolicai-main/assets/images/symai_logo.png deleted file mode 100644 index afe72b9d03e9720575d1d9a277defcf5b6e9e929..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/assets/images/symai_logo.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2fbd98ef18d93b8a4cbce766455dd8687f2b9f22b3a4be01988924a891f3afc4 -size 127115 diff --git a/symbolicai-main/symbolicai-main/assets/images/symsh.png b/symbolicai-main/symbolicai-main/assets/images/symsh.png deleted file mode 100644 index 3955b525511f8a2c3a328fa6f8e5c17a0624e06f..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/assets/images/symsh.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:60e6538bff0841d366aa50074da65e20309eb2d77084d0a6ecbd969edbb52e0e -size 103992 diff --git a/symbolicai-main/symbolicai-main/assets/images/vid1.png b/symbolicai-main/symbolicai-main/assets/images/vid1.png deleted file mode 100644 index b3f8a77e86645f1a7a3a1de3460f7359606d8620..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/vid1.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/vid2.png b/symbolicai-main/symbolicai-main/assets/images/vid2.png deleted file mode 100644 index ad373bbf053d7d2ce2a832ec2a1129f4c4ecbfaf..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/vid2.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/vid3.png b/symbolicai-main/symbolicai-main/assets/images/vid3.png deleted file mode 100644 index e3601b9acde20fd2104c59054a52f40670ef6a64..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/assets/images/vid3.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:098a21daa3da02c846a73c2b4ce18c171ccb0b5ab1f6218233060fbf6b3528f6 -size 141729 diff --git a/symbolicai-main/symbolicai-main/assets/images/vid4.png b/symbolicai-main/symbolicai-main/assets/images/vid4.png deleted file mode 100644 index 40514ef2405b9cb6e6ad0f6625e503760e00f166..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/vid4.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/vid5.png b/symbolicai-main/symbolicai-main/assets/images/vid5.png deleted file mode 100644 index 96f38d20c0572ceb2f10fd4e2925ddaae5847c70..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/vid5.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/images/vid6.png b/symbolicai-main/symbolicai-main/assets/images/vid6.png deleted file mode 100644 index 9a5038eb113d3f11d47f3e92848ddc54654cd049..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/assets/images/vid6.png and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/assets/results/news.html b/symbolicai-main/symbolicai-main/assets/results/news.html deleted file mode 100644 index cd6d4965b98aecb843d5f3daf37c2ac6db139444..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/assets/results/news.html +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - News - - - - - - -

News Headlines

-
-

Cybersecurity Consolidation and the Equifax Settlement

-

The upcoming year is likely to see a wave of cybersecurity consolidation, according to Jay Chaudhry, the CEO of Zscaler. This could be a major boon for stocks with high profit margins, which may rally by more than 50%. Consumers may also benefit from the Equifax settlement, receiving payments to help protect their online identities.

-

However, it is important to understand the risks associated with using password managers to protect your online identity. Password managers can be a useful tool, but they can also create a single point of failure, meaning if someone were to gain access to your password manager, they would have access to all of your passwords. Therefore, it is important to do your research before deciding to use one.

-

Other headlines

-
    -
  • Rch downgraded Palantir, suggesting that its stock could drop below $5. This news followed the arrest of two New York men for conspiring to hack the JFK taxi dispatch system.
  • -
  • Tech executives are prioritizing cloud computing and security, with CAPTCHA being used by Google and e-commerce businesses to battle bots.
  • -
  • The FBI is concerned about a crime wave against small businesses, and has released information about how much money is being lost as a result.
  • -
  • Quiet hiring is on the rise in the tech industry, as tech companies are looking to stealthily acquire top talent.
  • -
  • China is a major risk for companies operating in the US, as the US-China trade war is showing no signs of abating.
  • -
  • Tech execs are spending more, with the latest survey showing that spending on tech is increasing year-over-year.
  • -
  • FuboTV suffered a major cyberattack, with hackers gaining access to user data and bank accounts.
  • -
  • Cloudflare has recently reported strong cash flow, indicating that the cloud security firm is in a good position.
  • -
  • The White House is focusing on cybersecurity, with the President signing an executive order that outlines the government's commitment to cybersecurity.
  • -
  • LinkedIn is taking steps to combat fake accounts, with the social media giant introducing new measures to detect and remove fraudulent accounts.
  • -
  • Huawei is facing more licensing issues, with the US government continuing to pressure the Chinese tech giant.
  • -
  • TikTok is facing scrutiny over its data privacy practices, with the US government expressing serious concerns.
  • -
  • SentinelOne is reporting strong profitability, with the cybersecurity firm posting impressive results in the third quarter.
  • -
  • A new chip firm based in the US and the Netherlands has been announced, indicating that chipmakers are looking to diversify their operations.
  • -
  • CrowdStrike's stock is soaring, with the cyber security firm's stock price rising over 30% in the past month.
  • -
-
-
-

Technology Executives Council's Opening Keynote on Dec 12, 2022

-

The Technology Executive Council's opening keynote on Monday, December 12th 2022, will discuss the intersection of finance, technology and national security. A few days prior, on Saturday, December 10th 2022, a Cyber Report was released noting that LinkedIn has a problem with fake accounts and is actively trying to fix it. On Sunday, December 11th 2022, Huawei announced that it had licensed 5G patents to a rival as U.S. sanctions have forced the Chinese giant to seek out new revenue.

-

Other News

-
    -
  • On Thursday, December 8th 2022, a number of states took action against TikTok over data privacy concerns.
  • -
  • The following Wednesday, December 7th 2022, SentinelOne's CEO announced that the company was aiming to be profitable by FY25.
  • -
  • Tuesday, December 6th 2022, saw a globally critical chip firm creating a wedge between the United States and the Netherlands.
  • -
  • In the U.S., a look at what it takes to be considered middle class in 20 major cities.
  • -
  • Russia has blamed cellphones for a deadly attack in Makiivka, and President Putin has sent hypersonic cruise missiles to the Atlantic.
  • -
  • The U.S. could see a shift to "quiet hiring" in 2023, while the Mega Millions jackpot is now at $785 million.
  • -
  • China is posing a risk to American tech giants Tesla and Apple, and small business owners should take steps to protect themselves from hackers.
  • -
  • Tech executives are signaling that spending will increase in 2023, despite massive layoffs in the sector.
  • -
  • This was followed by a cyberattack on FuboTV during a World Cup semifinal match.
  • -
  • Cloudflare CEO Matthew Prince has stated that annual plans allow the company to have more free cash flow up-front.
  • -
  • The closing keynote addressed the White House's seriousness about cybersecurity, while the increase in Gmail spam regarding Yeti coolers was explained.
  • -
-
-
-
-
-

CrowdStrike Stock

-

Wednesday, November 30th 2022, saw CrowdStrike stock go down on earnings, but Morgan Stanley advised to buy the dip.

-
-
-

Fitness Trackers

-

Monday, November 28th 2022, a discussion was held on the biggest risks of utilizing fitness trackers to monitor health.

-
-
-
-
-

Tom Lee on Bitcoin

-

Friday, November 25th 2022, Fundstrat's Tom Lee spoke about how Bitcoin still makes sense for certain investors, and the same day the new iPhone 14 and iOS upgrade was released, including significant changes to cybersecurity.

-
-
-

Chainalysis CEO

-

On Tuesday, November 22nd 2022, Chainalysis' CEO Michael Gronager spoke about protecting customers from bad actors in the crypto space.

-
-
-
-
-

DraftKings

-

Monday, November 21st 2022, DraftKings declared that there was no evidence that their systems had been breached following a report of a hack. On the same day, a discussion was held on how BlackBerry had moved away from their iconic cellphones to focus on cybersecurity.

-
-
-

Cohesity CEO

-

Friday, November 18th 2022, Cohesity's CEO Sanjay Poonen discussed how cloud, data and security remain strong for software.

-
-
-
-
-

White House Cybersecurity Team

-

Sunday, November 20th 2022, the White House's cybersecurity team discussed the potential threat posed by China's TikTok.

-
-
-

Palo Alto's Overtime

-

Finally, on Friday, November 25th 2022, Palo Alto's Overtime was discussed.

-
-
-
-
-

Beats Acquisition (BA)

-

Beats recently announced that it had exceeded fourth quarter earnings estimates and that it had agreed to acquire Cider Security. As part of its ongoing expansion, Beats has also recently added CNBC on Peacock with an exclusive CNBC Panel.

-

In addition to its digital products, Beats also offers news releases, closed captioning, corrections, and information about CNBC, internships, and its site map. Beats also provides users with ad choices, career opportunities, help, and contact news tips.

-

Beats provides a great way for users to stay informed about the latest news and technology trends.

-
-
-
-
    -
  • Advertise with us
  • -
  • Access real-time snapshot global business and financial news
  • -
  • Stock quotes
  • -
  • Market data and analysis
  • -
- -Using the Bootstrap library, the content can be styled as follows: - -

We offer the following opportunities:

- -
    -
  • Advertise with us
  • -
  • Access real-time snapshot global business and financial news
  • -
  • Stock quotes
  • -
  • Market data and analysis
  • -
- - - - \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/assets/results/news.png b/symbolicai-main/symbolicai-main/assets/results/news.png deleted file mode 100644 index e9fb51c6f21bee3992dce5f2bd48b0746cd6ff9b..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/assets/results/news.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c5932bf9626e2647e4d5fd8592c18069b5da2cbdd7f571fc6b5d5f1fe95d4104 -size 621792 diff --git a/symbolicai-main/symbolicai-main/assets/results/news_prev.png b/symbolicai-main/symbolicai-main/assets/results/news_prev.png deleted file mode 100644 index d04ca0d6dbe2ce1a30d949af4aedaace0102f82e..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/assets/results/news_prev.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:897d26462069d9d451449d186113926bbd008150635e279a425eafa6363f31bf -size 118086 diff --git a/symbolicai-main/symbolicai-main/bin/install.ps1 b/symbolicai-main/symbolicai-main/bin/install.ps1 deleted file mode 100644 index 90a9fd690cbfa1b27b8539578b49ca4d0b82f2d7..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/bin/install.ps1 +++ /dev/null @@ -1,42 +0,0 @@ -# Check if Git is installed -if (-not (Get-Command git -ErrorAction SilentlyContinue)) { - # Download Git from the official site and install - Invoke-WebRequest -Uri "https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe" -OutFile "$env:TEMP\Git-2.31.0-64-bit.exe" - Start-Process "$env:TEMP\Git-2.31.0-64-bit.exe" -ArgumentList "/VERYSILENT" -Wait -} - -# Check if Anaconda installed -if (-not (Get-Command conda -ErrorAction SilentlyContinue)) { - # Download Anaconda from the official site and install - Invoke-WebRequest -Uri "https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Windows-x86_64.exe" -OutFile "$env:TEMP\Anaconda3-2023.03-1-Windows-x86_64.exe" - Start-Process "$env:TEMP\Anaconda3-2023.03-1-Windows-x86_64.exe" -ArgumentList "/InstallationType=JustMe /AddToPath=0 /RegisterPython=0 /S" -Wait -} - -# Source conda -$env:Path = "$env:USERPROFILE\Anaconda3\Scripts;" + $env:Path - -# Create conda environment named symenv -conda create --name symenv -y - -# Install Jupyter Notebook using conda -conda install -n symenv jupyter -y - -# Activate the conda environment -conda activate symenv - -# Install symbolicai using pip that comes with the Anaconda environment -& "$env:USERPROFILE\Anaconda3\envs\symenv\Scripts\pip" install symbolicai - -# Set up an ipython configuration -if (!(Test-Path -Path "$env:USERPROFILE\.ipython\profile_default\startup")) { - New-Item -ItemType directory -Path "$env:USERPROFILE\.ipython\profile_default\startup" -} -Add-Content "$env:USERPROFILE\.ipython\profile_default\startup\startup.py" "from symai import *; from symai.extended.conversation import Conversation; q = Conversation(auto_print=True)" - -# Create a shortcut for the ipython console on Desktop -$Shortcut = (New-Object -ComObject WScript.Shell).CreateShortcut("$([Environment]::GetFolderPath('Desktop'))\SymbolicAI.lnk") -$Shortcut.TargetPath = "powershell.exe" -$Shortcut.WorkingDirectory = "" # set this to the intended starting directory -$command = '-ExecutionPolicy Bypass -NoExit -Command . "$env:USERPROFILE\Anaconda3\envs\symenv\Scripts\ipython.exe"' -$Shortcut.Arguments = $command -$Shortcut.Save() diff --git a/symbolicai-main/symbolicai-main/bin/install.sh b/symbolicai-main/symbolicai-main/bin/install.sh deleted file mode 100644 index e0ac72b0f223b320ed9cc032d1fd4a8f64972ee2..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/bin/install.sh +++ /dev/null @@ -1,104 +0,0 @@ -#!/bin/bash -# Check if git is installed -if ! command -v git &> /dev/null -then - # Install git - if [ "$(uname)" == "Darwin" ]; then - # MacOS - /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" - brew install git - elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then - # Linux - sudo apt-get install git -y - fi -fi - -# Check if Anaconda and git are installed -if ! command -v conda &> /dev/null -then - # Check the OS to download the appropriate version of Anaconda - if [ "$(uname)" == "Darwin" ]; then - # MacOS - if [ "$(uname -m)" == "x86_64" ]; then - # Intel Mac - curl -O https://repo.anaconda.com/archive/Anaconda3-2023.03-1-MacOSX-x86_64.sh - bash Anaconda3-2023.03-1-MacOSX-x86_64.sh -b - else - # Apple Silicon Mac - curl -O https://repo.anaconda.com/archive/Anaconda3-2023.03-1-MacOSX-arm64.sh - bash Anaconda3-2023.03-1-MacOSX-arm64.sh -b - fi - elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then - # Linux - wget https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Linux-x86_64.sh - bash Anaconda3-2023.03-1-Linux-x86_64.sh -b - fi -fi - -# Initialize Anaconda3 -# Skip initialization if already initialized -if [ -z "$(conda info --envs)" ] -then - eval "$(conda shell.bash hook)" -fi - -# Source conda -source ~/anaconda3/etc/profile.d/conda.sh - -# Create conda environment named symai -conda create --name symenv -y - -# Install Jupyter Notebook using conda -conda install -n symenv jupyter -y - -# Activate the conda environment -conda activate symenv - -# Install symbolicai using pip that comes with the Anaconda environment -~/anaconda3/envs/symenv/bin/pip install symbolicai - -# Install ipython configuration -mkdir -p ~/.ipython/profile_default/startup -echo "from symai import *; from symai.extended.conversation import Conversation; q = Conversation(auto_print=True)" > ~/.ipython/profile_default/startup/startup.py - -# Create a desktop icon on Linux -if [ "$(uname)" == "Darwin" ]; then - # MacOS - # Generate open-terminal-and-run script - echo "#!/bin/bash - open -a Terminal.app ~/anaconda3/envs/symenv/bin/ipython" > SymbolicAI.app - - # Make the generated script executable - chmod +x SymbolicAI.app - - # Move the script to the Applications directory - mv SymbolicAI.app /Applications/SymbolicAI.app - - # Generate an Automator application that runs the script - echo " - - - - Label - com.user.loginscript - ProgramArguments - - /Applications/SymbolicAI.app - - RunAtLoad - - - " > ~/Library/LaunchAgents/com.user.loginscript.plist -elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then - # Linux - echo "[Desktop Entry] - Version=1.0 - Type=Application - Name=Sym AI - Icon=terminal - Exec=bash -c 'source ~/anaconda3/bin/activate symenv && ipython' - Terminal=true" > ~/Desktop/symai.desktop - - # Make the desktop file executable - chmod +x ~/Desktop/symai.desktop -fi \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/build.py b/symbolicai-main/symbolicai-main/build.py deleted file mode 100644 index 7f223c710c86c3a0041e09e0e11de782e11d3cfc..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/build.py +++ /dev/null @@ -1,562 +0,0 @@ -# build.py -import os -import platform -import shutil -import subprocess -import sys -from typing import Optional - - -class BuildConfig: - def __init__(self): - self.system = platform.system() - self.machine = platform.machine() - self.arch = self._determine_arch() - - def _determine_arch(self) -> str: - if self.machine == 'arm64' or self.machine == 'aarch64': - return 'arm64' - elif self.machine == 'x86_64' or self.machine == 'AMD64': - return 'x86_64' - else: - raise ValueError(f"Unsupported architecture: {self.machine}") - - @property - def is_apple_silicon(self) -> bool: - return self.system == 'Darwin' and self.arch == 'arm64' - - -# Add this function to build.py -def create_info_plist(app_dir: str, target_arch: str): - """Create Info.plist file for macOS app bundle.""" - info_plist = f""" - - - - CFBundleDisplayName - SymbolicAI Installer - CFBundleExecutable - SymbolicAI_Installer - CFBundleIconFile - icon.icns - CFBundleIdentifier - com.symbolicai.installer - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - SymbolicAI Installer - CFBundlePackageType - APPL - CFBundleShortVersionString - 1.0.0 - LSMinimumSystemVersion - 10.15.0 - NSHighResolutionCapable - - NSRequiresAquaSystemAppearance - - - -""" - plist_path = os.path.join(app_dir, 'Contents', 'Info.plist') - with open(plist_path, 'w') as f: - f.write(info_plist) - - -def create_spec_file(target_arch: str) -> str: - """Create a spec file for the target architecture.""" - spec_content = f"""# -*- mode: python ; coding: utf-8 -*- -import sys -import os -import customtkinter -from PyInstaller.utils.hooks import collect_all - -block_cipher = None - -# Collect all necessary packages -cts = collect_all('customtkinter') - -a = Analysis( - ['installer.py'], - pathex=[], - binaries=[], - datas=[ - *cts[0], # Binaries - *cts[1], # Datas - ], - hiddenimports=[*cts[2]], # Hidden imports - hookspath=[], - hooksconfig={{}}, - runtime_hooks=[], - excludes=[], - win_no_prefer_redirects=False, - win_private_assemblies=False, - cipher=block_cipher, - noarchive=False, - target_arch='{target_arch}' -) - -pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) - -if sys.platform == 'darwin': - exe = EXE( - pyz, - a.scripts, - [], - exclude_binaries=True, - name='SymbolicAI_Installer', - debug=False, - bootloader_ignore_signals=False, - strip=False, - upx=True, - console=False, - disable_windowed_traceback=False, - target_arch='{target_arch}', - codesign_identity=None, - entitlements_file=None, - icon='icon.icns' - ) - - # Bundle everything into the app - app = BUNDLE( - exe, - a.binaries, - a.zipfiles, - a.datas, - name='SymbolicAI_Installer-{target_arch}.app', - icon='icon.icns', - bundle_identifier='com.symbolicai.installer', - info_plist={{ - 'CFBundleShortVersionString': '1.0.0', - 'LSMinimumSystemVersion': '10.15.0', - 'NSHighResolutionCapable': True, - 'NSRequiresAquaSystemAppearance': False, - }}, - ) -else: - exe = EXE( - pyz, - a.scripts, - a.binaries, - a.zipfiles, - a.datas, - [], - name='SymbolicAI_Installer', - debug=False, - bootloader_ignore_signals=False, - strip=False, - upx=True, - upx_exclude=[], - runtime_tmpdir=None, - console=False, - disable_windowed_traceback=False, - target_arch='{target_arch}', - codesign_identity=None, - entitlements_file=None, - icon='icon.ico' if sys.platform == 'win32' else None - ) -""" - spec_file = f'installer_{target_arch}.spec' - with open(spec_file, 'w') as f: - f.write(spec_content) - return spec_file - - -def clean_build_dirs(): - """Clean up build directories.""" - dirs_to_clean = ['build', 'dist'] - for dir_name in dirs_to_clean: - if os.path.exists(dir_name): - shutil.rmtree(dir_name) - - -def ensure_icons(): - """Ensure icons are available before building.""" - if not os.path.exists('icon_converter.py'): - raise FileNotFoundError("icon_converter.py not found!") - subprocess.check_call(['python', 'icon_converter.py']) - - -def verify_executable_format(executable_path: str, target_arch: str): - """Verify the format of the executable.""" - try: - output = subprocess.check_output(['file', executable_path], text=True) - print(f"Executable format: {output.strip()}") - - if target_arch == 'x86_64': - if 'x86_64' not in output: - print(f"Warning: Executable {executable_path} is not in x86_64 format") - return False - elif target_arch == 'arm64': - if 'arm64' not in output: - print(f"Warning: Executable {executable_path} is not in arm64 format") - return False - return True - except subprocess.CalledProcessError as e: - print(f"Error checking executable format: {str(e)}") - return False - - -def verify_binary_architecture(binary_path: str, expected_arch: str): - """Verify the architecture of a binary.""" - try: - output = subprocess.check_output(['lipo', '-info', binary_path], text=True) - if expected_arch not in output: - print(f"Warning: Binary {binary_path} does not contain {expected_arch} architecture") - print(f"Architecture info: {output.strip()}") - return False - return True - except subprocess.CalledProcessError as e: - print(f"Error checking architecture: {str(e)}") - return False - - -def verify_mac_app(app_path: str): - """Verify the macOS app bundle.""" - try: - # Verify bundle structure - required_paths = [ - 'Contents/Info.plist', - 'Contents/MacOS/SymbolicAI_Installer', - 'Contents/Resources/icon.icns' - ] - - for path in required_paths: - full_path = os.path.join(app_path, path) - if not os.path.exists(full_path): - print(f"Warning: Missing {path}") - - # Verify signing of all components - try: - print("\nVerifying code signing:") - subprocess.check_call(['codesign', '--verify', '--verbose=4', app_path]) - print("Main bundle verification successful") - - # Verify all binaries in the bundle - for root, _, files in os.walk(app_path): - for file in files: - file_path = os.path.join(root, file) - try: - output = subprocess.check_output(['file', file_path], text=True) - if 'Mach-O' in output: - subprocess.check_call(['codesign', '--verify', file_path]) - print(f"Verified: {os.path.relpath(file_path, app_path)}") - except subprocess.CalledProcessError: - print(f"Warning: Signature verification failed for {file_path}") - except Exception: - continue - - # Check if app can be opened - subprocess.check_call(['spctl', '--assess', '--verbose=4', app_path]) - print("App passed system security assessment") - - except subprocess.CalledProcessError as e: - print(f"Warning: Verification failed: {str(e)}") - except FileNotFoundError: - print("Warning: Verification tools not found") - - except Exception as e: - print(f"Error verifying app bundle: {str(e)}") - - -def build_installer(target_arch: Optional[str] = None): - """Build the installer for the current platform and specified architecture.""" - config = BuildConfig() - - # Clean previous builds - clean_build_dirs() - - # Ensure correct Python architecture - if config.system == 'Darwin': - subprocess.run(['arch', f'-{target_arch}' if target_arch else '', - sys.executable, '-m', 'pip', 'install', '--upgrade', 'pip']) - subprocess.run(['arch', f'-{target_arch}' if target_arch else '', - sys.executable, '-m', 'pip', 'install', 'pyinstaller', 'customtkinter']) - - # Create spec file for target architecture - spec_file = create_spec_file(target_arch or config.arch) - - # Build command - build_cmd = ['pyinstaller', '--clean', '--noconfirm', spec_file] - - if config.system == 'Darwin': - build_cmd = ['arch', f'-{target_arch}'] + build_cmd if target_arch else build_cmd - - try: - # Execute build - subprocess.run(build_cmd, check=True) - - # Create platform-specific release folder - release_dir = f'release_{config.system.lower()}_{target_arch}' - if os.path.exists(release_dir): - shutil.rmtree(release_dir) - os.makedirs(release_dir) - - if config.system == 'Darwin': - app_name = f'SymbolicAI_Installer-{target_arch}.app' - final_app = f'{release_dir}/{app_name}' - - # Create proper bundle structure - os.makedirs(f'{final_app}/Contents/MacOS', exist_ok=True) - os.makedirs(f'{final_app}/Contents/Resources', exist_ok=True) - os.makedirs(f'{final_app}/Contents/Frameworks', exist_ok=True) - - # Find the built app in dist - dist_app = None - - # Look for the .app in dist directory - for item in os.listdir('dist'): - if item.endswith('.app'): - dist_app = os.path.join('dist', item) - break - - if not dist_app: - raise FileNotFoundError("Built .app not found in dist directory") - - # Copy the entire contents preserving structure - shutil.copytree(dist_app, final_app, dirs_exist_ok=True) - - # Ensure executable is in the correct location - executable_path = f'{final_app}/Contents/MacOS/SymbolicAI_Installer' - if not os.path.exists(executable_path): - # Look for the executable in the dist directory - for root, _, files in os.walk(dist_app): - for file in files: - if file == 'SymbolicAI_Installer': - src = os.path.join(root, file) - shutil.copy2(src, executable_path) - break - - # Copy icon - if os.path.exists('icon.icns'): - shutil.copy2('icon.icns', f'{final_app}/Contents/Resources/') - - # Create Info.plist - create_info_plist(final_app, target_arch) - - # Create entitlements file - create_entitlements() - - # Set permissions - os.chmod(executable_path, 0o755) - - # Set proper permissions - subprocess.run(['chmod', '-R', '+x', final_app], check=True) - - # Remove any existing signatures and extended attributes - subprocess.run(['xattr', '-cr', final_app], check=True) - - try: - # First, sign all frameworks and libraries - print("Signing frameworks and libraries...") - for root, _, files in os.walk(final_app): - for file in files: - file_path = os.path.join(root, file) - if file.endswith(('.so', '.dylib')) or 'Python' in file: - try: - print(f"Signing {file_path}") - subprocess.run([ - 'codesign', - '--force', - '--sign', '-', - '--timestamp', - '--verbose', - '--preserve-metadata=identifier,entitlements,requirements,flags,runtime', - file_path - ], check=True, capture_output=True, text=True) - except subprocess.CalledProcessError as e: - print(f"Warning: Failed to sign {file_path}") - print(f"Error: {e.stderr}") - - # Sign the main executable - print("Signing main executable...") - subprocess.run([ - 'codesign', - '--force', - '--sign', '-', - '--timestamp', - '--verbose', - '--options', 'runtime', - executable_path - ], check=True, capture_output=True, text=True) - - # Finally sign the entire bundle - print("Signing complete bundle...") - subprocess.run([ - 'codesign', - '--force', - '--sign', '-', - '--timestamp', - '--verbose', - '--deep', - '--options', 'runtime', - '--entitlements', 'entitlements.plist', - final_app - ], check=True, capture_output=True, text=True) - - except subprocess.CalledProcessError as e: - print(f"Code signing failed: {e.stderr}") - - # Verify the build - verify_mac_app(final_app) - - # Verify the executable format - verify_executable_format(executable_path, target_arch) - - except subprocess.CalledProcessError as e: - print(f"Build process failed: {str(e)}") - raise - except FileNotFoundError as e: - print(f"File not found error: {str(e)}") - raise - except Exception as e: - print(f"Unexpected error during build: {str(e)}") - raise - - -def create_release_zip(target_arch: str): - config = BuildConfig() - release_dir = f'release_{config.system.lower()}_{target_arch}' - archive_name = f'SymbolicAI_Installer_{config.system.lower()}_{target_arch}' - shutil.make_archive(archive_name, 'zip', release_dir) - - -def sign_mac_app(app_path: str): - """Sign all binaries in the macOS app bundle.""" - try: - # Remove any existing signatures first - subprocess.run(['xattr', '-cr', app_path], check=True) - - # Sign all binaries and libraries recursively - for root, _, files in os.walk(app_path): - for file in files: - file_path = os.path.join(root, file) - try: - output = subprocess.check_output(['file', file_path], text=True) - if 'Mach-O' in output: - subprocess.run([ - 'codesign', - '--force', - '--sign', - '-', - '--timestamp', - '--deep', - '--preserve-metadata=entitlements,requirements,flags,runtime', - file_path - ], check=True) - print(f"Signed: {file_path}") - except (subprocess.CalledProcessError, Exception) as e: - print(f"Warning: Could not sign {file_path}: {str(e)}") - continue - - # Finally sign the main bundle - subprocess.run([ - 'codesign', - '--force', - '--sign', - '-', - '--timestamp', - '--deep', - '--options', 'runtime', - '--entitlements', 'entitlements.plist', - app_path - ], check=True) - print(f"Successfully signed {app_path}") - except Exception as e: - print(f"Warning: Signing failed: {str(e)}") - - -def create_entitlements(entitlements_path: str = 'entitlements.plist'): - """Create entitlements file for macOS app.""" - entitlements = """ - - - - com.apple.security.cs.allow-unsigned-executable-memory - - com.apple.security.cs.allow-jit - - com.apple.security.cs.disable-library-validation - - com.apple.security.cs.debugger - - com.apple.security.get-task-allow - - com.apple.security.automation.apple-events - - com.apple.security.files.user-selected.read-write - - com.apple.security.files.downloads.read-write - - -""" - with open(entitlements_path, 'w') as f: - f.write(entitlements) - - -def build_universal_mac(): - """Build universal binary for macOS (Apple Silicon only).""" - config = BuildConfig() - if not config.is_apple_silicon: - print("Universal builds are only supported on Apple Silicon Macs") - return - - # Build for both architectures - build_installer('arm64') - build_installer('x86_64') - - # Verify the builds - verify_mac_app(f'release_darwin_arm64/SymbolicAI_Installer-arm64.app') - verify_mac_app(f'release_darwin_x86_64/SymbolicAI_Installer-x86_64.app') - - # Create universal build directory - universal_dir = 'release_darwin_universal' - if os.path.exists(universal_dir): - shutil.rmtree(universal_dir) - os.makedirs(f'{universal_dir}/SymbolicAI_Installer.app/Contents/MacOS') - - # Use lipo to create universal binary - subprocess.check_call([ - 'lipo', - 'release_darwin_arm64/SymbolicAI_Installer-arm64.app/Contents/MacOS/SymbolicAI_Installer', - 'release_darwin_x86_64/SymbolicAI_Installer-x86_64.app/Contents/MacOS/SymbolicAI_Installer', - '-create', - '-output', - f'{universal_dir}/SymbolicAI_Installer.app/Contents/MacOS/SymbolicAI_Installer' - ]) - - # Copy resources and Info.plist from arm64 build - shutil.copytree( - 'release_darwin_arm64/SymbolicAI_Installer-arm64.app/Contents/Resources', - f'{universal_dir}/SymbolicAI_Installer.app/Contents/Resources' - ) - shutil.copy2( - 'release_darwin_arm64/SymbolicAI_Installer-arm64.app/Contents/Info.plist', - f'{universal_dir}/SymbolicAI_Installer.app/Contents/Info.plist' - ) - - # Verify universal build - verify_mac_app(f'{universal_dir}/SymbolicAI_Installer.app') - - # Create zip for universal build - create_release_zip('universal') - - -if __name__ == '__main__': - config = BuildConfig() - - # Ensure icons are available - ensure_icons() - - if config.system == 'Darwin': - if config.is_apple_silicon: - # On Apple Silicon, build universal binary - build_universal_mac() - else: - # On Intel Mac, build only x86_64 - build_installer('x86_64') - create_release_zip('x86_64') - else: - # For other platforms, build for current architecture - build_installer() - create_release_zip(config.arch) \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/docker-compose.yml b/symbolicai-main/symbolicai-main/docker-compose.yml deleted file mode 100644 index e0f98e7cb2176cea37838813eca72716da649a62..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: '3.8' - -services: - symai_service: - build: - context: . - dockerfile: Dockerfile - image: extensityai/symbolicai:latest - command: uvicorn symai.endpoints.api:app --reload --host 0.0.0.0 --port 8999 - ports: - - 8999:8999 - volumes: - - .symai:/root/.symai diff --git a/symbolicai-main/symbolicai-main/docs/source/ENGINES/clip_engine.md b/symbolicai-main/symbolicai-main/docs/source/ENGINES/clip_engine.md deleted file mode 100644 index 7dee95aa203665ffdd5ab251d4179502591aea3b..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/ENGINES/clip_engine.md +++ /dev/null @@ -1,25 +0,0 @@ -# CLIP Engine - ---- - -## ⚠️ Outdated or Deprecated Documentation ⚠️ -This documentation is outdated and may not reflect the current state of the SymbolicAI library. This page might be revived or deleted entirely as we continue our development. We recommend using more modern tools that infer the documentation from the code itself, such as [DeepWiki](https://deepwiki.com/ExtensityAI/symbolicai). This will ensure you have the most accurate and up-to-date information and give you a better picture of the current state of the library. - ---- - -To perform text-based image few-shot classification, we use `CLIP`. This implementation is very experimental, and conceptually does not fully integrate the way we intend it, since the embeddings of CLIP and GPT-3 are not aligned (embeddings of the same word are not identical for both models). Aligning them remains an open problem for future research. For example, one could learn linear projections from one embedding space to the other. - -The following example demonstrates how to classify the image of our generated cat from above and return the results as an array of probabilities: - -```python -clip = Interface('clip') -res = clip('https://oaidalleapiprodscus.blob.core.windows.net/private/org-l6FsXDfth6...', - ['cat', 'dog', 'bird', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe']) -``` - -```bash -:Output: -array([[9.72840726e-01, 6.34790864e-03, 2.59368378e-03, 3.41371237e-03, - 3.71197984e-03, 8.53193272e-03, 1.03346225e-04, 2.08464009e-03, - 1.77942711e-04, 1.94185617e-04]], dtype=float32) -``` diff --git a/symbolicai-main/symbolicai-main/docs/source/ENGINES/custom_engine.md b/symbolicai-main/symbolicai-main/docs/source/ENGINES/custom_engine.md deleted file mode 100644 index 4730ff480e852255f19a90fb5d1e4b46dbc7a1f5..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/ENGINES/custom_engine.md +++ /dev/null @@ -1,81 +0,0 @@ -# Custom Engine - -If you want to replace or extend the functionality of our framework, you can do so by customizing the existing engines or creating new engines. -To create and use any other LLM as a backend you can for example change the `neurosymbolic` engine setting and register the new engine to the `EngineRepository`. The following example shows how to create a new `neurosymbolic` engine: - -```python -from symai.backend.base import Engine -from symai.functional import EngineRepository - -# setup an engine -class MyEngine(Engine): - def id(self): - return 'neurosymbolic' - - def prepare(self, argument): - # get input from the pre-processors output and use *args, **kwargs and prop from argument - # argument.prop contains all your kwargs accessible via dot `.` operation and additional meta info - # such as function signature, system relevant info etc. - prompts = argument.prop.preprocessed_input - args = argument.args - kwargs = argument.kwargs - # prepare the prompt statement as you want (take a look at the other engines like for GPT-4) - ... - # assign it to prepared_input - argument.prop.prepared_input = ... - - def forward(self, argument): - # get prep statement - prompt = argument.prop.prepared_input - # Your API / engine related call code here - return ... - -# register your engine -EngineRepository.register('neurosymbolic', engine, allow_engine_override=True) -``` - -Any engine is derived from the base class `Engine` and is then registered in the engines repository using its registry ID. The ID is for instance used in `core.py` decorators to address where to send the zero/few-shot statements using the class `EngineRepository`. You can find the `EngineRepository` defined in `functional.py` with the respective `query` method. Every engine has therefore three main methods you need to implement. The `id`, `prepare` and `forward` method. The `id` return the engine category. The `prepare` and `forward` methods have a signature variable called `argument` which carries all necessary pipeline relevant data. For instance, the output of the `argument.prop.preprocessed_input` contains the pre-processed output of the `PreProcessor` objects and is usually what you need to build and pass on to the `argument.prop.prepared_input`, which is then used in the `forward` call. - -If you don't want to re-write the entire engine code but overwrite the existing prompt `prepare` logic, you can do so by subclassing the existing engine and overriding the `prepare` method. - -Here is an example of how to initialize your own engine. We will subclass the existing `GPTXChatEngine` and override the `prepare` method. This method is called before the neural computation and can be used to modify the input prompt's parameters that will be passed in for execution. In this example, we will replace the prompt with dummy text for illustration purposes: - -```python -import os - -from symai import Expression, Symbol -from symai.backend.engines.neurosymbolic.engine_openai_gptX_chat import \ - GPTXChatEngine -from symai.functional import EngineRepository - - -class DummyEngine(GPTXChatEngine): - def __init__(self): - super().__init__(model='gpt-4o-mini', api_key=os.getenv('OPENAI_API_KEY', 'your-api-key-here')) - - def prepare(self, argument): - argument.prop.prepared_input = [ - {'role': 'system', 'content': 'Write like Jack London!'}, - {'role': 'user', 'content': 'Go wild and generate something!'} - ] - -custom_engine = DummyEngine() -sym = Symbol() -EngineRepository.register('neurosymbolic', custom_engine, allow_engine_override=True) -res = sym.compose() -print(res) -``` - -To configure an engine, we can forward commands through `Expression` objects by using the `command` method. The `command` method passes on configurations (as `**kwargs`) to the engines and change functionalities or parameters. The functionalities depend on the respective engine. - -In this example, we will enable `verbose` mode, where the engine will print out the methods it is executing and the parameters it is using. This is useful for debugging purposes: - -```python -from symai import Expression - -sym = Symbol('Hello World!') -Expression.command(engines=['neurosymbolic'], verbose=True) -res = sym.translate('German') -``` - -Finally, if you want to create a completely new engine but still maintain our workflow, you can use the `query` function from [`symai/functional.py`](https://github.com/ExtensityAI/symbolicai/blob/main/symai/functional.py) and pass in your engine along with all other specified objects (i.e., Prompt, PreProcessor, etc). diff --git a/symbolicai-main/symbolicai-main/docs/source/ENGINES/drawing_engine.md b/symbolicai-main/symbolicai-main/docs/source/ENGINES/drawing_engine.md deleted file mode 100644 index 029dfb33f09a345a7a06878daa98ce5ae3fbf42d..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/ENGINES/drawing_engine.md +++ /dev/null @@ -1,163 +0,0 @@ -# Drawing Engine - -We now expose two distinct high-level drawing interfaces: - -1. **`gpt_image`** – a unified wrapper around OpenAI’s Images API (DALL·E 2/3 and `gpt-image-*`). -2. **`flux`** – Black Forest Labs’ Flux text-to-image models via api.us1.bfl.ai. - -Both return a list of local PNG file paths. - ---- - -## 1. OpenAI “gpt_image” Interface - -Use `Interface('gpt_image')` to drive OpenAI’s Images API. -Supported models: -- `dall-e-2` -- `dall-e-3` -- `gpt-image-1` - -### Example: Create - -```python -from symai.interfaces import Interface - -gpt_image = Interface('gpt_image') - -paths = gpt_image( - "a fluffy cat with a cowboy hat", - operation="create", # create | variation | edit - model="dall-e-3", # choose your model - n=1, # number of images - size=1024, # square size in px, or "1024x1024" - response_format="url", # "url" or "b64_json" - # Extra for DALL·E-3: - quality="standard", # "standard" | "hd" - style="vivid", # "vivid" | "natural" - # Extra for gpt-image-*: - moderation="auto", # "auto" | "strict" - background="transparent", # "auto" | "transparent" - output_compression="png", # "png" | "jpeg" | "webp" - # if jpeg/webp you can also pass `output_compression=80` for quality -) - -print(paths[0]) # → /tmp/tmpabcd.png -``` - -### Example: Variation - -```python -from symai.interfaces import Interface -from pathlib import Path - -gpt_image = Interface('gpt_image') - -paths = gpt_image( - operation="variation", - model="dall-e-2", - image_path=Path("assets/images/cat.png"), - n=3, - size=512, - response_format="url", -) -``` - -### Example: Edit - -```python -from symai.interfaces import Interface -from pathlib import Path - -gpt_image = Interface('gpt_image') - -paths = gpt_image( - "Add medieval armor and scrolls in the background", - operation="edit", - model="gpt-image-1", - image_path=Path("assets/images/cat.png"), - mask_path=Path("assets/images/cat-mask.png"), # optional - n=1, - size=512, - quality="medium", # only for gpt-image-* -) -``` - -### Supported Parameters - -**Common** (all operations): - -- `prompt` (str) -- `operation` (`"create"`|`"variation"`|`"edit"`) -- `model` (str) -- `n` (int, default=1) -- `size` (int or `"WxH"`) -- `response_format` (`"url"`|`"b64_json"`) - -**Create-only**: - -- DALL·E-3: - - `quality` (`"standard"`|`"hd"`) - - `style` (`"vivid"`|`"natural"`) -- gpt-image-*: - - `quality` (`"auto"`|`"low"`|`"medium"`|`"high"`) - - `moderation` (`"auto"`|`"strict"`) - - `background` (`"auto"`|`"transparent"`) - - `output_compression` (`"png"`|`"jpeg"`|`"webp"` or integer) - -**Variation / Edit**: - -- `image_path` (Path or str or list) -- `mask_path` (Path or str, edit only) - ---- - -## 2. Black Forest Labs “flux” Interface - -Use `Interface('flux')` to call Flux via https://api.us1.bfl.ai. -Supported models: any `flux-*`, e.g. configured in `SYMAI_CONFIG["DRAWING_ENGINE_MODEL"]`. - -### Example - -```python -from symai.interfaces import Interface - -flux = Interface('flux') - -paths = flux( - "a futuristic city skyline at night", - operation="create", # currently only 'create' is implemented - model="flux-pro-1.1", - width=1024, # default 1024 - height=768, # default 768 - steps=50, # default 40 - guidance=7.5, # default None - seed=42, # default None - safety_tolerance=2, # default 2 - prompt_upsampling=False, # default False - interval=5, # default None - output_format="png", # default 'png' -) - -print(paths) # → ['/tmp/tmp1234.png'] -``` - -### Supported Parameters - -- `model` (str) -- `width` (int, default 1024) -- `height` (int, default 768) -- `steps` (int, default 40) -- `guidance` (float) -- `seed` (int) -- `safety_tolerance` (int, default 2) -- `prompt_upsampling` (bool, default False) -- `interval` (int) -- `output_format` (str, default 'png') -- `except_remedy` (callable) - -Under the hood Flux uses: - -- POST `https://api.us1.bfl.ai/v1/{model}` -- GET `https://api.us1.bfl.ai/v1/get_result?id={request_id}` - -and writes out local PNG file(s). diff --git a/symbolicai-main/symbolicai-main/docs/source/ENGINES/file_engine.md b/symbolicai-main/symbolicai-main/docs/source/ENGINES/file_engine.md deleted file mode 100644 index 89c078ea9b8bca1b5d6c8e2fc9d61ead16164db9..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/ENGINES/file_engine.md +++ /dev/null @@ -1,8 +0,0 @@ -# File Engine - -To perform file operations, we use the operating system's file system. Currently, we support only PDF files and plain text files. This is an early stage, and we are working on more sophisticated file system access and remote storage. The following example demonstrates how to read a PDF file and return the text: - -```python -from symai import Symbol -res = Symbol('./LICENSE').open() -``` diff --git a/symbolicai-main/symbolicai-main/docs/source/ENGINES/indexing_engine.md b/symbolicai-main/symbolicai-main/docs/source/ENGINES/indexing_engine.md deleted file mode 100644 index d7d2139a86d587c9e4b64dcb0ea74cc573e57e7b..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/ENGINES/indexing_engine.md +++ /dev/null @@ -1,22 +0,0 @@ -# Indexing Engine - ---- - -## ⚠️ Outdated or Deprecated Documentation ⚠️ -This documentation is outdated and may not reflect the current state of the SymbolicAI library. This page might be revived or deleted entirely as we continue our development. We recommend using more modern tools that infer the documentation from the code itself, such as [DeepWiki](https://deepwiki.com/ExtensityAI/symbolicai). This will ensure you have the most accurate and up-to-date information and give you a better picture of the current state of the library. - ---- - -We use `Pinecone` to index and search for text. The following example demonstrates how to store text as an index and then retrieve the most related match: - -```python -expr = Expression() -expr.add(Symbol('Hello World!').zip()) -expr.add(Symbol('I like cookies!').zip()) -res = expr.get(Symbol('hello').embedding, index_name='default_index').ast() -res['matches'][0]['metadata']['text'][0] -``` - -Here, the `zip` method creates a pair of strings and embedding vectors, which are then added to the index. The line with `get` retrieves the original source based on the vector value of `hello` and uses `ast` to cast the value to a dictionary. - -You can set several optional arguments for the indexing engine. For more details, see the `symai/backend/engine_pinecone.py` file. diff --git a/symbolicai-main/symbolicai-main/docs/source/ENGINES/local_engine.md b/symbolicai-main/symbolicai-main/docs/source/ENGINES/local_engine.md deleted file mode 100644 index 2fe3c69d47b89ace8e92e932c1bc49a764dfaeee..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/ENGINES/local_engine.md +++ /dev/null @@ -1,125 +0,0 @@ -# Local Engines -## Local Neuro-Symbolic Engine - -You can use a locally hosted instance for the Neuro-Symbolic Engine. We build on top of: -- [llama.cpp](https://github.com/ggerganov/llama.cpp/tree/master) either through: - - Direct C++ server from llama.cpp - - [llama-cpp-python](https://github.com/abetlen/llama-cpp-python?tab=readme-ov-file) -- [huggingface/transformers](https://huggingface.co/docs/transformers/en/index) through a custom FastAPI server. - -### llama.cpp backend -For instance, let's suppose you want to set as a Neuro-Symbolic Engine the latest Llama 3 model. First, download the model with the HuggingFace CLI: -```bash -huggingface-cli download TheBloke/LLaMA-Pro-8B-Instruct-GGUF llama-pro-8b-instruct.Q4_K_M.gguf --local-dir . -``` - -With `symai`, first set the `NEUROSYMBOLIC_ENGINE_MODEL` to `llamacpp`: - -```json -{ - "NEUROSYMBOLIC_ENGINE_API_KEY": "", - "NEUROSYMBOLIC_ENGINE_MODEL": "llamacpp", - ... -} -``` - -You can then run the server in two ways: - -1. Using Python bindings: -```bash -symserver --env python --model ./llama-pro-8b-instruct.Q4_K_M.gguf --n_gpu_layers -1 --chat_format llama-3 --port 8000 --host localhost -``` - -2. Using C++ server directly: -```bash -symserver --env cpp --cpp-server-path /path/to/llama.cpp/server -m ./llama-pro-8b-instruct.Q4_K_M.gguf --port 8000 --host localhost -``` - -To see all available options, run: -```bash -symserver --env python --help # for Python bindings -symserver --env cpp --cpp-server-path /path/to/llama.cpp/server --help # for C++ server -``` - -### HuggingFace backend -Let's suppose we want to use `dolphin-2.9.3-mistral-7B-32k` from HuggingFace. First, download the model with the HuggingFace CLI: -```bash -huggingface-cli download cognitivecomputations/dolphin-2.9.3-mistral-7B-32k --local-dir ./dolphin-2.9.3-mistral-7B-32k -``` - -For the HuggingFace server, you have to set the `NEUROSYMBOLIC_ENGINE_MODEL` to `huggingface`: -```json -{ - "NEUROSYMBOLIC_ENGINE_API_KEY": "", - "NEUROSYMBOLIC_ENGINE_MODEL": "huggingface", - ... -} -``` - -Then, run `symserver` with the following options: -```bash -symserver --model ./dolphin-2.9.3-mistral-7B-32k --attn_implementation flash_attention_2 -``` - -To see all the available options we support for HuggingFace, run: -```bash -symserver --help -``` - -Now you are set to use the local engine. - -```python -# do some symbolic computation with the local engine -sym = Symbol('Kitties are cute!').compose() -print(sym) - -# :Output: -# Kittens are known for their adorable nature and fluffy appearance, making them a favorite addition to many homes across the world. They possess a strong bond with -# their owners, providing companionship and comfort that can ease stress and anxiety. With their playful personalities, they are often seen as a symbol of happiness -# and joy, and their unique characteristics such as purring, kneading, and head butts bring warmth to our hearts. Cats also have a natural instinct to groom, which -# helps them maintain their clean and soft fur. Not only do they bring comfort and love to their owners, but they also have some practical benefits, such as reducing -# allergens, deterring pests, and even reducing stress in their surroundings. Overall, it is no surprise that pets have a long history of providing both emotional -# and physical comfort and happiness to their owners, making them a much-loved member of families around the world. -``` - -## Local Embedding Engine -You can also use local embedding models through the `llama.cpp` backend. First, set the `EMBEDDING_ENGINE_MODEL` to `llamacpp`: - -```json -{ - "EMBEDDING_ENGINE_API_KEY": "", - "EMBEDDING_ENGINE_MODEL": "llamacpp", - ... -} -``` - -For instance, to use the Nomic embed text model, first download it: -```bash -huggingface-cli download nomic-ai/nomic-embed-text-v1.5-GGUF nomic-embed-text-v1.5.Q8_0.gguf --local-dir . -``` - -Then start the server with embedding-specific parameters using either: - -Python bindings: -```bash -symserver --env python --model nomic-embed-text-v1.5.Q8_0.gguf --embedding True --n_ctx 2048 --rope_scaling_type 2 --rope_freq_scale 0.75 --n_batch 32 --port 8000 --host localhost -``` - -C++ server: -```bash -symserver --env cpp --cpp-server-path /path/to/llama.cpp/server -ngl 0 -m nomic-embed-text-v1.5.Q8_0.gguf --embedding -c 8192 -b 8192 --rope-scaling yarn --rope-freq-scale .75 --port 8000 --host localhost -``` - -The server supports batch processing for embeddings. Here's how to use it with `symai`: - -```python -from symai import Symbol - -# Single text embedding -some_text = "Hello, world!" -embedding = Symbol(some_text).embed() # returns a list (1 x dim) - -# Batch processing -some_batch_of_texts = ["Hello, world!"] * 32 -embeddings = Symbol(some_batch_of_texts).embed() # returns a list (32 x dim) -``` diff --git a/symbolicai-main/symbolicai-main/docs/source/ENGINES/neurosymbolic_engine.md b/symbolicai-main/symbolicai-main/docs/source/ENGINES/neurosymbolic_engine.md deleted file mode 100644 index b6055f79d33d501ff48cfed18f2ad21cd6b24c50..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/ENGINES/neurosymbolic_engine.md +++ /dev/null @@ -1,353 +0,0 @@ -# Neuro-Symbolic Engine - -The **neuro-symbolic** engine is our generic wrapper around large language models (LLMs) that support prompts, function/tool calls, vision tokens, token‐counting/truncation, etc. -Depending on which backend you configure (OpenAI/GPT, Claude, Gemini, Deepseek, llama.cpp, HuggingFace, …), a few things must be handled differently: - -* GPT-family (OpenAI) and most backends accept the usual `max_tokens`, `temperature`, etc., out of the box. -* Claude (Anthropic), Gemini (Google), and Deepseek can return an internal “thinking trace” when you enable it. -* Local engines (llamacpp, HuggingFace) do *not* yet support token counting, JSON format enforcement, or vision inputs in the same way. -* Token‐truncation and streaming are handled automatically but may vary in behavior by engine. - -**Note**: the most accurate documentation is the _code_, so be sure to check out the tests. Look for the `mandatory` mark since those are the features that were tested and are guaranteed to work. - ---- - -## Basic Query - -```python -from symai import Symbol, Expression - -# A one-off question -res = Symbol("Hello, world!").query("Translate to German.") -print(res.value) -# → "Hallo, Welt!" -``` - -Under the hood this uses the `neurosymbolic` engine. - ---- - -## Raw LLM Response - -If you need the raw LLM objects (e.g. `openai.ChatCompletion`, `anthropic.types.Message`/`anthropic.Stream`, or `google.genai.types.GenerateContentResponse`), use `raw_output=True`: - -```python -from symai import Expression - -raw = Expression.prompt("What is the capital of France?", raw_output=True) -# raw.value is the LLM response object -``` - ---- - -## Function/Tool Calls - -Models that support function calls (OpenAI GPT-4, Claude, Gemini, …) can dispatch to your `symai.components.Function` definitions: - -```python -from symai.components import Function - -tools = [{ - "type": "function", - "function": { - "name": "get_weather", - "description": "Get current temperature for a location.", - "parameters": { - "type": "object", - "properties": { - "location": {"type": "string"} - }, - "required": ["location"] - } - } -}] - -fn = Function( - "Choose and call the appropriate function", - tools=tools -) - -# GPT-style tool call -resp = fn("What's the temperature in Bogotá, Colombia?", raw_output=True) -# resp.choices[0].finish_reason == "tool_calls" -# resp.choices[0].message.tool_calls[0].function.name == "get_weather" -``` - -For Claude the API shapes differ slightly: - -```python -from anthropic.types import ToolUseBlock - -tools = [ - { - "name": "get_stock_price", - "description": "Get stock price for a ticker.", - "input_schema": { … } - } -] -fn = Function("Pick a function", tools=tools) - -# Enable thinking trace (see next section) if needed -resp = fn("What's the S&P 500 today?", raw_output=True, thinking=thinking, max_tokens=16000) -blocks = [b for b in resp.content if isinstance(b, ToolUseBlock)] -assert blocks[0].name == "get_stock_price" -``` - ---- - -## Thinking Trace (Claude, Gemini & Deepseek) - -Some engines (Anthropic's Claude, Google's Gemini, Deepseek) can return an internal **thinking trace** that shows how they arrived at an answer. To get it, you must: - -1. Pass `return_metadata=True`. -2. Pass a `thinking=` configuration if required. -3. Inspect `metadata["thinking"]` after the call. - -### Claude (Anthropic) - -```python -from symai import Symbol - -thinking = {"budget_tokens": 4092} - -res, metadata = Symbol("Topic: Disneyland") \ - .query( - "Write a dystopic take on the topic.", - return_metadata=True, - thinking=thinking, - max_tokens=16_000 - ) -print(res.value) -print(metadata["thinking"]) -``` - -### Gemini (Google) - -```python -from symai import Symbol - -thinking = {"thinking_budget": 1024} - -res, metadata = Symbol("Topic: Disneyland") \ - .query( - "Write a dystopic take on the topic.", - return_metadata=True, - thinking=thinking - ) -print(res.value) -print(metadata["thinking"]) -``` - -### Deepseek - -```python -from symai import Symbol - -# Deepseek returns thinking by default if you enable metadata -res, metadata = Symbol("Topic: Disneyland") \ - .query( - "Write a dystopic take on the topic.", - return_metadata=True - ) -print(res.value) -print(metadata["thinking"]) -``` - ---- - -## JSON‐Only Responses - -To force the model to return valid JSON and have `symai` validate it: - -```python -import json -from symai import Expression - -admin_role = "system" # or "developer" for non-GPT backends - -resp = Expression.prompt( - message=[ - {"role": admin_role, "content": "You output valid JSON."}, - {"role": "user", "content": ( - "Who won the world series in 2020?" - " Return as { 'team':'str','year':int,'coach':'str' }" - )} - ], - response_format={"type": "json_object"}, - suppress_verbose_output=True -) -data = json.loads(resp.value) -# data == {"team":"Los Angeles Dodgers", "year":2020, "coach":"Dave Roberts"} -``` - ---- - -## Token Counting & Truncation - -The default pipeline will automatically estimate token usage and truncate conversation as needed. -On GPT-family backends, raw API usage in `response.usage` matches what `symai` computes. -For Gemini, an API call is made to retrieve token counts. -For Claude / llama.cpp / HuggingFace, skip token‐comparison tests as they are not uniformly supported yet. - -If a tokenizer is available for the current engine, you can easily count tokens in a string via `Symbol`: -```python -string = "Hello, World!" -print(Symbol(string).tokens) -``` - -### Tracking Usage and Estimating Costs with `MetadataTracker` - -For more detailed tracking of API calls, token usage, and estimating costs, you can use the `MetadataTracker` in conjunction with `RuntimeInfo`. This is particularly useful for monitoring multiple calls within a specific code block. -> Note: we only track OpenAI models for now (chat and search). - -`MetadataTracker` collects metadata from engine calls made within its context. `RuntimeInfo` then processes this raw metadata to provide a summary of token counts, number of API calls, elapsed time, and an estimated cost if pricing information is provided. - -Here's an example of how to use them: - -```python -import time -from symai import Symbol, Interface -from symai.components import MetadataTracker -from symai.utils import RuntimeInfo -from symai.backend.settings import SYMAI_CONFIG - -# This is a simplified cost estimation function. -# It's called for each engine's usage data. -def estimate_cost_for_engine(info: RuntimeInfo, pricing: dict) -> float: - # Cost calculation including cached tokens and per-call costs. - # Assumes 'pricing' dict contains 'input', 'cached_input', 'output', and optionally 'calls' keys. - input_cost = (info.prompt_tokens - info.cached_tokens) * pricing.get("input", 0) - cached_input_cost = info.cached_tokens * pricing.get("cached_input", 0) - output_cost = info.completion_tokens * pricing.get("output", 0) - call_cost = info.total_calls * pricing.get("calls", 0) # Cost for the number of API calls - return input_cost + cached_input_cost + output_cost + call_cost - -# This check is illustrative; adapt as needed for your environment. -NEUROSYMBOLIC_ENGINE_IS_OPENAI = 'gpt' in SYMAI_CONFIG.get('NEUROSYMBOLIC_ENGINE_MODEL', '').lower() -SEARCH_ENGINE_IS_OPENAI = 'gpt' in SYMAI_CONFIG.get('SEARCH_ENGINE_MODEL', '').lower() - -if NEUROSYMBOLIC_ENGINE_IS_OPENAI and SEARCH_ENGINE_IS_OPENAI: - sym = Symbol("This is a context sentence.") - # We'll assume 'openai_search' interface maps to an engine like 'GPTXSearchEngine' or similar. - # This engine name should then be a key in your dummy_pricing dictionary. - search = Interface('openai_search') - start_time = time.perf_counter() - with MetadataTracker() as tracker: - res = sym.query("What is the capital of France?") - search_res = search("What are the latest developments in AI?") - end_time = time.perf_counter() - - # Dummy pricing for cost estimation. - # Keys are tuples of (engine_name, model_id) and should match the keys - # that appear in the tracker.usage dictionary. These depend on your SYMAI_CONFIG - # and the models used by the engines. - dummy_pricing = { - ("GPTXChatEngine", "gpt-model-A"): { # Example: engine used by sym.query() and its model - "input": 0.000002, - "cached_input": 0.000001, - "output": 0.000002 - }, - ("GPTXSearchEngine", "gpt-model-B"): { # Example: engine used by Interface('openai_search') and its model - "input": 0.000002, - "cached_input": 0.000001, - "output": 0.000002, - "calls": 0.0001 # Cost per API call - } - # Add other (engine_name, model_id) tuples and their pricing if used. - } - - # Process collected data: - # RuntimeInfo.from_tracker returns a dictionary where keys are (engine_name, model_id) tuples - # and values are RuntimeInfo objects for each engine-model combination. - # We pass 0 for total_elapsed_time initially, as it's set for the aggregated sum later. - usage_per_engine = RuntimeInfo.from_tracker(tracker, 0) - - # Initialize an empty RuntimeInfo object to aggregate totals - aggregated_usage = RuntimeInfo( - total_elapsed_time=0, - prompt_tokens=0, - completion_tokens=0, - reasoning_tokens=0, - cached_tokens=0, - total_calls=0, - total_tokens=0, - cost_estimate=0 - ) - for (engine_name, model_id), engine_data in usage_per_engine.items(): - pricing_key = (engine_name, model_id) - if pricing_key in dummy_pricing: - # Estimate cost for this specific engine and model - engine_data_with_cost = RuntimeInfo.estimate_cost(engine_data, estimate_cost_for_engine, pricing=dummy_pricing[pricing_key]) - aggregated_usage += engine_data_with_cost # Aggregate data - # Set the total elapsed time for the aggregated object - aggregated_usage.total_elapsed_time = end_time - start_time -``` - -This approach provides a robust way to monitor and control costs associated with LLM API usage, especially when making multiple calls. Remember to update the `pricing` dictionary with the current rates for the models you are using. The `estimate_cost` function can also be customized to reflect complex pricing schemes (e.g., different rates for different models, image tokens, etc.). - ---- - -## Preview Mode - -When building new `Function` objects, preview mode lets you inspect the *prepared* prompt **before** calling the engine: - -```python -from symai.components import Function - -preview_fn = Function( - "Return a JSON markdown string.", - static_context="Static…", - dynamic_context="Dynamic…" -) -# Instead of executing, retrieve prop.processed_input -preview = preview_fn("Hello, World!", preview=True) -assert preview.prop.processed_input == "Hello, World!" -``` - ---- - -## Self-Prompting - -If you want the model to “self-prompt” (i.e. use the original symbol text as context): - -```python -from symai import Symbol - -sym = Symbol("np.log2(2)", self_prompt=True) -res = sym.query("Is this equal to 1?", self_prompt=True) -assert "yes" in res.value.lower() -``` - ---- - -## Vision Inputs - -Vision tokens (e.g. `<>`) can be passed in prompts on supported backends: - -```python -from pathlib import Path -from symai import Symbol - -file = Path("assets/images/cat.jpg") -res = Symbol(f"<>").query("What is in the image?") -assert "cat" in res.value.lower() -``` - -Skip this on llama/HuggingFace if not implemented. - ---- - -## Summary - -The neuro-symbolic engine is your central entry point for all LLM-based operations in `symai`. -By tweaking flags such as `return_metadata`, `raw_output`, `preview`, and `thinking`, you can: - -- extract low-level API objects, -- retrieve internal thought traces, -- preview prompts before hitting the API, -- enforce JSON formats, -- handle function/tool calls, -- feed in vision data, -- and let `symai` manage token‐truncation automatically. - -Refer to the individual engine docs (OpenAI, Claude, Gemini, Deepseek, llama.cpp, HuggingFace) for any model-specific quirks. diff --git a/symbolicai-main/symbolicai-main/docs/source/ENGINES/ocr_engine.md b/symbolicai-main/symbolicai-main/docs/source/ENGINES/ocr_engine.md deleted file mode 100644 index a709226d4a120b15aed723cccff96564aadf5e60..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/ENGINES/ocr_engine.md +++ /dev/null @@ -1,18 +0,0 @@ -# OCR Engine - ---- - -## ⚠️ Outdated or Deprecated Documentation ⚠️ -This documentation is outdated and may not reflect the current state of the SymbolicAI library. This page might be revived or deleted entirely as we continue our development. We recommend using more modern tools that infer the documentation from the code itself, such as [DeepWiki](https://deepwiki.com/ExtensityAI/symbolicai). This will ensure you have the most accurate and up-to-date information and give you a better picture of the current state of the library. - ---- -To extract text from images, we can perform optical character recognition (OCR) with `APILayer`. The following example demonstrates how to transcribe an image and return the text: - -```python -from symai.interfaces import Interface - -ocr = Interface('ocr') -res = ocr('https://media-cdn.tripadvisor.com/media/photo-p/0f/da/22/3a/rechnung.jpg') -``` - -The OCR engine returns a dictionary with a key `all_text` where the full text is stored. For more details, refer to their documentation [here](https://apilayer.com/marketplace/image_to_text-api). diff --git a/symbolicai-main/symbolicai-main/docs/source/ENGINES/search_engine.md b/symbolicai-main/symbolicai-main/docs/source/ENGINES/search_engine.md deleted file mode 100644 index 49997306190e519defce11d341e0d68068e93ea7..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/ENGINES/search_engine.md +++ /dev/null @@ -1,116 +0,0 @@ -# Search Engine - -To obtain fact-based content, we can perform search queries via `SerpApi` with a `Google` backend. The following example demonstrates how to search for a query and return the results: - -```python -from symai.interfaces import Interface - -search = Interface('serpapi') -res = search('Birthday of Barack Obama') -``` - -```bash -:Output: -August 4, 1961 -``` - -Here's a quick example for how to set it up: -```bash -{ - … - "SEARCH_ENGINE_API_KEY": …, - "SEARCH_ENGINE_ENGINE": "google", - … -} -``` - -We can also use PerplexityAI to search for a query and return the results: - -```python -from symai.interfaces import Interface -search = Interface("perplexity") -res = search('What is a quantum computer?', system_message='You are Rick from Rick and Morty. You reply back as Rick would reply to Morty.') -``` - -```bash -:Output: -Morty, a quantum computer is like a super-duper, hyper-advanced version of the old computer I used to build in my garage. It uses the principles of quantum mechanics to process information in ways that classical computers can't even dream of. - -Here's the deal: instead of using those boring old bits that are either 0 or 1, quantum computers use something called qubits. These qubits can exist in multiple states at the same time, thanks to this weird phenomenon called superposition. It's like when you flip a coi -n and it's both heads and tails until you look at it—same idea, Morty. - -And then there's entanglement. This means that if you have two qubits, the state of one can depend on the state of the other, no matter how far apart they are. It's like having a secret handshake with your buddy that works even if you're on opposite sides of the multive -rse. - -So, with these qubits and their superposition and entanglement, quantum computers can perform calculations at speeds that would make even the most powerful supercomputers look like they're running on a Commodore 64. They can simulate molecular interactions, break encryp -tion codes faster than you can say "Wubba lubba dub dub," and solve problems that are currently unsolvable for classical computers. - -Now, if you'll excuse me, I have some real science to attend to. Don't get too excited, Morty; it's still just a bunch of fancy math and physics. But hey, it's cool stuff, right? -``` - -Please note that the system_message is optional and can be used to provide context to the model. For all available kwargs that can be passed to the perplexity engine, please refer to the PerplexityAI documentation. Also, please see the available supported engines for PerplexityAI here. Here's a quick example for how to set it up: - -```bash -{ - … - "SEARCH_ENGINE_API_KEY": "pplx-…", - "SEARCH_ENGINE_MODEL": "sonar", - … -} -``` - -Additionally, we can use OpenAI's search capabilities to answer queries and get citations for the information: - -```python -from symai.interfaces import Interface -search = Interface("openai_search") -res = search('Who is Nicusor Dan?') -``` - -```bash -:Output: -"As of May 20, 2025, the acting president of Romania is Ilie Bolojan. He assumed this role on February 12, 2025, following the resignation of Klaus Iohannis. Bolojan, a member of the National Liberal Party, previously served as the president of the Senate and the mayor of Oradea. [1]\n\nRomania held a presidential election on May 18, 2025, in which Nicușor Dan, the current mayor of Bucharest, was elected as the new president. Dan, an independent candidate endorsed by several pro-European Union parties, won the election with 53.6% of the vote, defeating nationalist candidate George Simion. [2] He is expected to be inaugurated as president in the near future.\n\n\n## Nicușor Dan's Victory in Romanian Presidential Election:\n- [3]\n- [4]\n- [5] " -``` - -The OpenAI search engine returns a `SearchResult` object that includes citations for the information. You can access these citations using: - -```python -citations = res.get_citations() -``` - -The engine supports various customization options, such as specifying user location and timezone: - -```python -# Search with user location -res = search("What are popular tourist attractions nearby?", - user_location={ - "type": "approximate", - "country": "US", - "city": "New York", - "region": "New York" - }) - -# Search with timezone -res = search("What local events are happening today?", - user_location={ - "type": "approximate", - "country": "JP", - "city": "Tokyo", - "region": "Tokyo", - "timezone": "Asia/Tokyo" - }) - -# Control the amount of search context -res = search("Explain quantum computing developments", search_context_size="high") -``` - -Here's how to configure the OpenAI search engine: - -```bash -{ - … - "SEARCH_ENGINE_API_KEY": "sk-…", - "SEARCH_ENGINE_MODEL": "gpt-4.1-mini", - … -} -``` diff --git a/symbolicai-main/symbolicai-main/docs/source/ENGINES/speech_engine.md b/symbolicai-main/symbolicai-main/docs/source/ENGINES/speech_engine.md deleted file mode 100644 index 24474c03c9b091e2bccfc1df28e1933c7ec45dc4..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/ENGINES/speech_engine.md +++ /dev/null @@ -1,10 +0,0 @@ -# Speech Engine (Whisper) - -To transcribe audio files, we can perform speech transcription using `whisper`. The following example demonstrates how to transcribe an audio file and return the text: - -```python -from symai.interfaces import Interface - -speech = Interface('whisper') -res = speech('examples/audio.mp3') -``` diff --git a/symbolicai-main/symbolicai-main/docs/source/ENGINES/symbolic_engine.md b/symbolicai-main/symbolicai-main/docs/source/ENGINES/symbolic_engine.md deleted file mode 100644 index 19ebacc5d04ca5c459b3114caa00ab891917a86e..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/ENGINES/symbolic_engine.md +++ /dev/null @@ -1,21 +0,0 @@ -# Symbolic Engine (WolframAlpha) - ---- - -## ⚠️ Outdated or Deprecated Documentation ⚠️ -This documentation is outdated and may not reflect the current state of the SymbolicAI library. This page might be revived or deleted entirely as we continue our development. We recommend using more modern tools that infer the documentation from the code itself, such as [DeepWiki](https://deepwiki.com/ExtensityAI/symbolicai). This will ensure you have the most accurate and up-to-date information and give you a better picture of the current state of the library. - ---- - -Although our work primarily emphasizes how LLMs can assess symbolic expressions, many formal statements have already been efficiently implemented in existing symbolic engines, such as WolframAlpha. Therefore, with an API KEY from WolframAlpha, we can use their engine by using the `Interface('wolframalpha')`. This avoids error-prone evaluations from neuro-symbolic engines for mathematical operations. The following example demonstrates how to use WolframAlpha to compute the result of the variable `x`: - -```python -from symai import Interface -expression = Interface('wolframalpha') -res = expression('x^2 + 2x + 1') -``` - -```bash -:Output: -x = -1 -``` diff --git a/symbolicai-main/symbolicai-main/docs/source/ENGINES/webcrawler_engine.md b/symbolicai-main/symbolicai-main/docs/source/ENGINES/webcrawler_engine.md deleted file mode 100644 index 0bb6b7cbdf5f944155556c1dff7b6f7c2e0322d0..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/ENGINES/webcrawler_engine.md +++ /dev/null @@ -1,23 +0,0 @@ -# Webcrawler Engine - ---- - -## ⚠️ Outdated or Deprecated Documentation ⚠️ -This documentation is outdated and may not reflect the current state of the SymbolicAI library. This page might be revived or deleted entirely as we continue our development. We recommend using more modern tools that infer the documentation from the code itself, such as [DeepWiki](https://deepwiki.com/ExtensityAI/symbolicai). This will ensure you have the most accurate and up-to-date informatio and give you a better picture of the current state of the library. - ---- -To access data from the web, we can use `Selenium`. The following example demonstrates how to crawl a website and return the results: - -```python -from symai.interfaces import Interface - -crawler = Interface('selenium') -res = crawler(url="https://www.google.com/", - pattern="google") -``` -The `pattern` property can be used to verify if the document has been loaded correctly. If the pattern is not found, the crawler will timeout and return an empty result. - -```bash -:Output: -GoogleKlicke hier, wenn du nach einigen Sekunden nicht automatisch weitergeleitet wirst.GmailBilderAnmelden ... -``` diff --git a/symbolicai-main/symbolicai-main/docs/source/FEATURES/contracts.md b/symbolicai-main/symbolicai-main/docs/source/FEATURES/contracts.md deleted file mode 100644 index 68727ab04236a4df944da716c03167521ac66e66..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/FEATURES/contracts.md +++ /dev/null @@ -1,604 +0,0 @@ -# Ensuring Correctness with Contracts - -In SymbolicAI, the `@contract` decorator provides a powerful mechanism, inspired by Design by Contract (DbC) principles, to enhance the reliability and semantic correctness of `Expression` classes, especially those interacting with Large Language Models (LLMs). It allows you to define explicit pre-conditions, post-conditions, and intermediate processing steps, guiding the behavior of your classes and the underlying LLMs. The original post introducing this feature can be found [here](https://futurisold.github.io/2025-03-01-dbc/). - -## Why Use Contracts? - -Traditional software development often relies on testing to verify correctness after the fact. Contracts, however, encourage building correctness into the design itself. When working with LLMs, which are inherently probabilistic, ensuring that outputs are not only syntactically valid but also semantically meaningful and contextually appropriate is crucial. - -Contracts in SymbolicAI help bridge this gap by: - -1. **Enforcing Semantic Guarantees**: Beyond static type checking (which ensures structural validity), contracts allow you to define and validate what your `Expression`'s inputs and outputs *mean* in a given context. -2. **Guiding LLM Behavior**: The error messages raised by failed pre-conditions and post-conditions are used as corrective prompts, enabling the LLM to attempt self-correction. This turns validation failures into learning opportunities for the model. -3. **Proactive Structuring**: Designing a contract forces careful consideration of inputs, outputs, and invariants, shifting from reactive validation to proactive structuring of your logic. -4. **Improving Predictability and Reliability**: By setting clear expectations and validation steps, contracts make your AI components more predictable and less prone to unexpected or undesirable outputs (like hallucinations). -5. **Enhancing Composability**: Clear contracts at the interface level allow different components (potentially powered by different LLMs or even rule-based systems) to interoperate reliably, as long as they satisfy the agreed-upon contractual obligations. - -## What is a `@contract` in SymbolicAI? - -The `@contract` is a class decorator that you apply to your custom classes inheriting from `symai.Expression`. It augments your class, particularly its `forward` method, by wrapping it with a validation and execution pipeline. - -Key characteristics: - -* **Operates on `LLMDataModel`**: Inputs to and outputs from the core contract-validated logic *must* be instances of `symai.models.LLMDataModel` (which extends Pydantic's `BaseModel`). This allows for structured data validation and rich schema descriptions that can inform LLM prompts. -* **User-Defined Conditions**: You define the contract's terms by implementing specific methods: `pre` (pre-conditions), `act` (optional intermediate action), and `post` (post-conditions), along with a `prompt` property. -* **Fallback Mechanism**: A contract never entirely prevents the execution of your class's original `forward` method. If contract validation fails (even after remedies), your `forward` method is still called (typically with the original, unvalidated input, if the failure happened before `act`, or the `act`-modified input if failure was in `post`), allowing you to implement fallback logic or return a default, type-compliant object. -* **State and Results**: The decorator adds attributes to your class instance: - * `self.contract_successful` (bool): Indicates if all contract validations (including remedies) passed. - * `self.contract_result` (Any): Holds the validated and potentially remedied output if successful; otherwise, it might be `None` or an intermediate value if an error occurred before `_validate_output` completed successfully. - * `self.contract_perf_stats()` (method): Returns a dictionary with performance metrics for various stages of the contract execution. - -## Core Components of a Contracted Class - -To use the `@contract` decorator, you'll define several key components within your `Expression` subclass: - -### 1. The `@contract` Decorator - -Apply it directly above your class definition: - -```python -from symai import Expression -from symai.strategy import contract -from symai.models import LLMDataModel -from typing import Optional, List # For type hints in examples - -# Default retry parameters used if not overridden in the decorator call -DEFAULT_RETRY_PARAMS = { - "tries": 5, "delay": 0.5, "max_delay": 15, - "jitter": 0.1, "backoff": 2, "graceful": False -} - -@contract( - pre_remedy: bool = False, - post_remedy: bool = True, - accumulate_errors: bool = False, - verbose: bool = False, - remedy_retry_params: dict = DEFAULT_RETRY_PARAMS # Uses defined defaults -) -class MyContractedClass(Expression): - # ... class implementation ... - pass -``` - -**Decorator Parameters and Defaults**: - -* `pre_remedy` (bool, default: `False`): - If `True`, attempts to automatically correct input validation failures (from your `pre` method) using LLM-based semantic remediation. -* `post_remedy` (bool, default: `True`): - If `True`, attempts to automatically correct output validation failures (from your `post` method or type mismatches) using LLM-based type and semantic remediation. -* `accumulate_errors` (bool, default: `False`): - Controls whether error messages from multiple failed validation attempts (during remediation) are accumulated and provided to the LLM in subsequent retry attempts. See more details in the "Error Accumulation" section below. -* `verbose` (bool, default: `False`): - If `True`, enables detailed logging of the contract's internal operations, including prompts sent to the LLM and validation steps. -* `remedy_retry_params` (dict, default: `{ "tries": 5, "delay": 0.5, "max_delay": 15, "jitter": 0.1, "backoff": 2, "graceful": False }`): - A dictionary configuring the retry behavior for both type and semantic validation/remediation functions. - * `tries` (int): Maximum number of retry attempts for a failed validation. - * `delay` (float): Initial delay (in seconds) before the first retry. - * `max_delay` (float): The maximum delay between retries. - * `jitter` (float): A factor for adding random jitter to delays to prevent thundering herd problems. - * `backoff` (float): The multiplier for increasing the delay between retries (e.g., 2 means delay doubles). - * `graceful` (bool): If `True`, suppresses exceptions during retry exhaustion and might allow the process to continue with a potentially invalid state (behavior depends on the specific validation function). Typically `False` for contracts to ensure failures are robustly handled. - -### 2. Input and Output Data Models - -Your contract's core logic (especially `pre`, `act`, `post`, and `forward`) will operate on instances of `LLMDataModel`. Define these models using Pydantic syntax. Crucially, use `Field(description=\"...\")` for your model attributes, as these descriptions are used to generate more effective prompts for the LLM. Always use descriptive `Field(description=\"...\")` for your type data models, as these descriptions are crucial for guiding the LLM effectively during validation and generation steps. Rich descriptions help the `TypeValidationFunction` understand the semantic intent of each field, leading to better error messages and more accurate data generation when remedies are active. - -```python -from pydantic import Field - -class MyInput(LLMDataModel): - text: str = Field(description="The input text to be processed.") - max_length: Optional[int] = Field(default=None, description="Optional maximum length for processing.") - -class MyIntermediate(LLMDataModel): - processed_text: str = Field(description="Text after initial processing by 'act'.") - entities_found: List[str] = Field(default_factory=list, description="Entities identified in 'act'.") - -class MyOutput(LLMDataModel): - result: str = Field(description="The final processed result.") - is_valid: bool = Field(description="Indicates if the result is considered valid by post-conditions.") -``` - -### 3. The `prompt` Property - -Your class must define a `prompt` property that returns a string. This prompt provides the high-level instructions or context to the LLM for the main task your class is designed to perform. It's particularly used by `TypeValidationFunction` (when semantic checks are guided by `pre`/`post` conditions and remedies are active) during the input (`pre_remedy`) and output (`post_remedy`) validation and remediation phases. - -```python - @property - def prompt(self) -> str: - return "You are an expert assistant. Given the input text, process it and return a concise summary." -``` - -**Important Note on Prompts:** A contract's `prompt` should be considered fixed. Its role is to describe the fundamental task the contract must perform and should not mutate during the lifetime of the contract instance or based on specific inputs. If you have dynamic instructions or data that changes with each call, this should not be part of the `prompt` string itself. Instead, create a state object or pass such dynamic information as part of your input data model (e.g., a field named `dynamic_instruction` or similar). The `prompt` defines *what* the contract does in general, while the input provides the specific data for *that particular execution*. - -### Error Accumulation (`accumulate_errors`) - -The `accumulate_errors` parameter (default: `False`) in the `@contract` decorator influences how the underlying `TypeValidationFunction` (which handles both type and semantic validation, including remedies) handles repeated failures during the remedy process. - -* **When `accumulate_errors = True`**: - If a validation (e.g., a `post`-condition) fails, and a remedy attempt also fails, the error message from this failed remedy attempt is stored. If subsequent remedy attempts also fail, their error messages are appended to the list of previous errors. This accumulated list of errors is then provided as part of the context to the LLM in the next retry. - * **Benefits**: This can be very useful in complex scenarios. By seeing the history of what it tried and why those attempts were flagged as incorrect, the LLM might gain a better understanding of the constraints and be less likely to repeat the same mistakes. It's like showing the LLM its "thought process" and where it went wrong, potentially leading to more effective self-correction. This is particularly helpful if an initial fix inadvertently introduces a new problem that was previously not an issue, or if a previously fixed error reappears. - * **Potential Downsides**: In some cases, providing a long list of past errors (especially if they are somewhat contradictory or if the LLM fixed an issue that then reappears in the error list) could confuse the LLM. It might lead to an overly complex prompt that makes it harder for the model to focus on the most recent or critical issue. - -* **When `accumulate_errors = False` (Default)**: - Only the error message from the most recent failed validation/remedy attempt is provided to the LLM for the next retry. The history of previous errors is not explicitly passed. - * **Benefits**: This keeps the corrective prompt focused and simpler, potentially being more effective for straightforward errors where historical context isn't necessary or could be distracting. - * **Potential Downsides**: The LLM loses the context of previous failed attempts. It might retry solutions that were already found to be problematic or might reintroduce errors that it had previously fixed in an earlier iteration of the remedy loop for the same overall validation step. - -Choosing whether to enable `accumulate_errors` depends on the complexity of your validation logic and how you observe the LLM behaving during remediation. If you find the LLM cycling through similar errors or reintroducing past mistakes, setting `accumulate_errors=True` might be beneficial. If the remediation prompts become too noisy or confusing, `False` might be preferable. - -### 4. The `pre(self, input: MyInput) -> bool` Method - -This method defines the pre-conditions for your contract. It's called with the validated input object (`current_input` in `strategy.py`, which has already passed the `_is_valid_input` type check). - -* **Signature**: `def pre(self, input: YourInputModel) -> bool:` -* **Behavior**: - * If all pre-conditions are met, it should do nothing or simply `return True`. (Note: The `bool` return type is conventional; the primary success signal is the absence of an exception). - * If a pre-condition is violated, it **must raise an exception**. The exception's message should be descriptive, as it will be used to guide the LLM if `pre_remedy` is enabled. - -```python - def pre(self, input: MyInput) -> bool: - if not input.text: - raise ValueError("Input text cannot be empty. Please provide some text to process.") - if input.max_length is not None and len(input.text) > input.max_length: - raise ValueError(f"Input text exceeds maximum length of {input.max_length}. Please provide shorter text.") - return True -``` - -### 5. The `act(self, input: MyInput, **kwargs) -> MyIntermediate` Method (Optional) - -The `act` method provides an optional intermediate processing step that occurs *after* input pre-validation (and potential pre-remedy) and *before* the main output validation/generation phase (`_validate_output`). - -* **Signature**: `def act(self, input: YourInputModelOrActInputModel, **kwargs) -> YourIntermediateModel:` - * The `input` parameter **must be named `input`** and be type-hinted with an `LLMDataModel` subclass. - * It must have a return type annotation, also an `LLMDataModel` subclass. This can be a different type than the input, allowing `act` to transform the data. - * `**kwargs` from the original call (excluding `'input'`) are passed to `act`. -* **Behavior**: - * Perform transformations on the `input`, computations, or state updates on `self`. - * The object returned by `act` becomes the `current_input` for the `_validate_output` stage (where the LLM is typically called to generate the final output type). - * Can modify `self` (e.g., update instance counters, accumulate history). - -```python - # Example: Add a counter to the class for state mutation - # def __init__(self, *args, **kwargs): - # super().__init__(*args, **kwargs) - # self.calls_count = 0 - - def act(self, input: MyInput, **kwargs) -> MyIntermediate: - # self.calls_count += 1 # Example of state mutation - processed_text = input.text.strip().lower() - # Example: simple entity "extraction" - entities = [word for word in processed_text.split() if len(word) > 5] - return MyIntermediate(processed_text=processed_text, entities_found=entities) -``` - -### 6. The `post(self, output: MyOutput) -> bool` Method - -This method defines the post-conditions. It's called by `_validate_output` with an instance of the `forward` method's declared return type (e.g., `MyOutput`). This instance is typically generated by an LLM call within `_validate_output` based on your class's `prompt` and the (potentially `act`-modified) input. - -* **Signature**: `def post(self, output: YourOutputModel) -> bool:` -* **Behavior**: - * If all post-conditions are met, `return True`. - * If a post-condition is violated, **raise an exception** with a descriptive message. This message guides LLM self-correction if `post_remedy` is enabled. - -```python - def post(self, output: MyOutput) -> bool: - if not output.result: - raise ValueError("The final result string cannot be empty.") - if output.is_valid is False and len(output.result) < 10: - raise ValueError("If result is marked invalid, it should at least have a short explanation (min 10 chars).") - # Example: could use self.custom_threshold modified by act - # if hasattr(self, 'custom_threshold') and output.some_score < self.custom_threshold: - # raise ValueError("Score too low based on dynamic threshold.") - return True -``` - -### 7. The `forward(self, input: MyInput, **kwargs) -> MyOutput` Method - -This is your class's original `forward` method, containing the primary logic. The `@contract` decorator wraps this method. - -* **Signature**: `def forward(self, input: YourInputModel, **kwargs) -> YourOutputModel:` - * The `input` parameter **must be named `input`** and be type-hinted with an `LLMDataModel` subclass that matches (or is compatible with) the input to `pre` and `act`. - * It **must have a return type annotation** (e.g., `-> YourOutputModel`), which must be an `LLMDataModel` subclass. This declared type is crucial for the contract's type validation and output generation phases. - * It **must not use positional arguments (`*args`)**; only keyword arguments are supported for the main input. Other `**kwargs` are passed through to the neurosymbolic engine. -* **Behavior**: - * This method is **always called** by the contract's `wrapped_forward` (in its `finally` block), regardless of whether the preceding contract validations (`pre`, `act`, `post`, remedies) succeeded or failed. - * **Developer Responsibility**: Inside your `forward` method, you *must* check `self.contract_successful` and/or `self.contract_result`. - * If `self.contract_successful` is `True`, `self.contract_result` holds the validated (and possibly remedied) output from the contract pipeline. You should typically return this. - * If `self.contract_successful` is `False`, the contract failed. `self.contract_result` might be `None` or an intermediate (invalid) object. In this case, your `forward` method should implement fallback logic: - * Return a sensible default object that matches `YourOutputModel`. - * Or, if appropriate, raise a custom exception (though the pattern encourages graceful fallback). - * The `input` argument received by *this* `forward` method (the one you write) depends on whether the contract succeeded: - * If `contract_successful == True`: `input` is the `current_input` from `wrapped_forward` which was used by `_validate_output`. This `current_input` is the output of `_act` if `act` is defined, otherwise it's the output of `_validate_input`. - * If `contract_successful == False`: `input` is the `original_input` (the raw input to the contract call, after initial type validation by `_is_valid_input` but before `pre` or `act` modifications). - -```python - - def forward(self, input: MyInput, **kwargs) -> MyOutput: - if not self.contract_successful or self.contract_result is None: - # Contract failed, or result is not set: implement fallback - return MyOutput(result="Error: Processing failed due to contract violation.", is_valid=False) - - # Contract succeeded, self.contract_result holds the validated output - # You can do further processing on self.contract_result if needed, - # or simply return it. - final_result: MyOutput = self.contract_result - final_result.result += " (Forward processed)" # Example of further work - return final_result -``` - -### Ensuring Meaningful Output: The Importance of `pre` and `post` Conditions - -It's quite easy to end up with a meaningless, "gibberish" object if you never really validate its contents. The role of `pre` and `post` conditions is exactly that: to ensure not just the shape but also the substance of your data. - -Before, the system might have returned a dummy filler object by default, even before the prompt was passed into the type-validation function. Now, while the prompt is wired through that function and the object should populate more sensibly, a core principle remains: - -> If the `post` method doesn't fail – either because no `ValueError` was thrown or because you skipped all semantic checks (e.g., by simply having `post` return `True`) – the contract will happily hand you back whatever came out of the type-validation step. - -Since the `TypeValidationFunction` (which handles the type-validation step) primarily enforces "is this a valid instance of the target type?" and doesn't inherently care what the fields contain beyond basic type conformance, you might get dummy values or inadequately populated fields unless you specify richer constraints. - -So, if your `LLMDataModel` types lack meaningful `Field(description="...")` attributes and your `prompt` isn't explicit enough, you might just get randomness or minimally populated objects. This is expected behavior. The contract pattern isn't broken; it's doing exactly what you told it to: validate shape, and substance *only if you explicitly define checks for it*. - -To illustrate, say you want a non-trivial `title: str` in your output object, but you never write a `post` check to validate its content (e.g., `if not output.title or len(output.title) < 10: raise ValueError("Title is missing or too short")`). In such a case, you might keep receiving a placeholder string or an inadequately generated title. While passing the main prompt into the `TypeValidationFunction` helps it try to generate something relevant, without a `post`-condition to enforce your specific requirements, you might still see undesirable behavior. - -**In short: the contract pattern is doing its job. If you want substance, you must codify those semantic rules in your `LLMDataModel` field descriptions and, critically, in your `pre` and `post` validation checks.** - -## Contract Execution Flow - -When you call an instance of your contracted class (e.g., `my_instance(input=my_input_data)`), the `wrapped_forward` method (created by the `@contract` decorator) executes the following sequence: - -1. **Initial Input Validation (`_is_valid_input`)**: - * Checks if the provided `input` kwarg is an instance of `LLMDataModel`. Fails fast if not. - * Extracts the `original_input` object. - -2. **Pre-condition Validation (`_validate_input`)**: - * The `current_input` (initially `original_input`) is passed to your `pre(input)` method. - * If `pre()` raises an exception and `pre_remedy=True`, `SemanticValidationFunction` attempts to correct the `current_input` based on the exception message from `pre()` and your class's `prompt`. - * If `pre()` raises and `pre_remedy=False` (or remedy fails), an `Exception("Pre-condition validation failed!")` is raised (this exception is then handled by `wrapped_forward`'s main `try...except` block). - -3. **Intermediate Action (`_act`)**: - * If your class defines an `act` method: - * Its signature is validated (parameter named `input`, `LLMDataModel` type hints for input and output). - * `act(current_input, **act_kwargs)` is called. `current_input` here is the output from the pre-condition validation step. - * The result of `act` becomes the new `current_input`. - * The actual type of `act`'s return value is checked against its annotation. - * If no `act` method, `current_input` remains unchanged. - -4. **Output Validation & Generation (`_validate_output`)**: - * This is a critical step, especially when `post_remedy=True`. - * It uses `TypeValidationFunction` and (if `post_remedy=True`) `SemanticValidationFunction`. - * The goal is to produce an object that matches your `forward` method's return type annotation (e.g., `MyOutput`). - * The `current_input` (which is the output from `_act`, or from `_validate_input` if no `act`) and your class's `prompt` are used to guide an LLM call to generate/validate data conforming to the target output type. - * Your `post(output)` method is called with the LLM-generated/validated output object. - * If `post()` raises an exception and `post_remedy=True`, remediation is attempted. - * If all these steps (type validation, LLM generation, `post` validation, remedies) succeed: - * `self.contract_successful` is set to `True`. - * `self.contract_result` is set to the final, validated output object. - * This output is typically assigned to `final_output` within the `try` block of `wrapped_forward` (the method created by the decorator). - -5. **Exception Handling in Main Path (`wrapped_forward`'s `try...except`)**: - * Steps 2, 3, and 4 (pre-validation, act, and output validation/generation) are wrapped in a `try...except Exception as e:` block within the decorator's logic. - * If any exception occurs during these steps (e.g., an unrecoverable failure in `_validate_input`, `_act`, or `_validate_output`), the `logger` records it, and `self.contract_successful` is set to `False`. - -6. **Final Execution (`finally` block of `wrapped_forward`)**: - * This block **always executes**, regardless of success or failure in the preceding `try` block. - * It determines the `forward_input` for your original `forward` method: - * If `self.contract_successful` is `True`, `forward_input` is the `current_input` that successfully passed through `_act` and was used by `_validate_output`. - * If `self.contract_successful` is `False`, `forward_input` is the `original_input`. - * Your class's original `forward(self, input=forward_input, **kwargs)` method is called. - * The value returned by *your* `forward` method becomes the ultimate return value of the contract call. - * A final output type check is performed on this returned value against your `forward` method's declared return type annotation. - -## Example -This is a 0-shot example generated by o3 from the above documentation and tests. - -```python -# ────────────────────────────────────────────────────────────── -# Standard library │ -# ────────────────────────────────────────────────────────────── -from typing import List, Optional - -from pydantic import Field - -# ────────────────────────────────────────────────────────────── -# SymbolicAI core │ -# ────────────────────────────────────────────────────────────── -from symai import Expression # Base class for your LLM “operators” -from symai.models import LLMDataModel # Thin Pydantic wrapper w/ LLM hints -from symai.strategy import contract # The Design-by-Contract decorator - -# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ -# 1. Data models ▬ -# – clear structure + rich Field descriptions power ▬ -# validation, automatic prompt templating & remedies ▬ -# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ - -class Document(LLMDataModel): - """Represents an entire document in the tiny in-memory corpus.""" - id: str = Field(description="Unique identifier of the document.") - content: str = Field(description="The full raw text of the document.") - - -class DocSnippet(LLMDataModel): - """ - Exact passage taken *verbatim* from a Document. - We store the `doc_id` so the answer can cite its source. - """ - doc_id: str = Field(description="ID of the document the snippet comes from.") - snippet: str = Field(description="A short excerpt supporting the answer.") - - -class MultiDocQAInput(LLMDataModel): - """ - The *input* to the contract call: - • the user’s natural-language question - • the corpus it may answer from - • a caller-specified upper bound on how many snippets can be cited - """ - query: str = Field(description="User question in plain English.") - documents: List[Document] = Field(description="Corpus to search for answers.") - max_snippets: Optional[int] = Field( - default=3, - ge=1, - le=10, - description="Max number of snippets the agent may cite (defaults to 3).", - ) - - -class IntermediateRetrieved(LLMDataModel): - """ - Returned by `act()`: lightweight retrieval result that will be fed to - the LLM so it can see relevant sentences without scanning whole docs. - """ - query: str = Field(description="The original question from the user.") - top_docs: List[Document] = Field(description="Top-k most relevant documents.") - selected_sentences: List[str] = Field( - description="Sentences deemed most relevant to the query." - ) - target_snippet_count: int = Field( - description="Upper bound on evidence snippets (copied from input)." - ) - - -class AnswerWithEvidence(LLMDataModel): - """ - Final object returned to the **caller** (and validated by `post`). - """ - answer: str = Field(description="Concise, stand-alone answer.") - evidence: List[DocSnippet] = Field(description="Cited supporting passages.") - coverage_score: float = Field( - ge=0.0, - le=1.0, - description=( - "LLM-estimated fraction of answer that is directly supported by the " - "evidence (0 = no support, 1 = fully supported)." - ), - ) - -# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ -# 2. The contracted class ▬ -# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ -@contract( - # ── Remedies ─────────────────────────────────────────── # - pre_remedy=True, # Try to fix bad inputs automatically - post_remedy=True, # Try to fix bad LLM outputs automatically - accumulate_errors=True, # Feed history of errors to each retry - verbose=True, # Log internal steps (see `symai.strategy` logger) - remedy_retry_params=dict(tries=3, delay=0.4, max_delay=4.0, - jitter=0.15, backoff=1.8, graceful=False), -) -class MultiDocQAgent(Expression): - """ - High-level behaviour: - 1. `pre` – sanity-check query & docs - 2. `act` – *retrieve* relevant sentences, mutate state - 3. LLM – generate AnswerWithEvidence (handled by SymbolicAI engine) - 4. `post` – ensure answer & evidence meet semantic rules - 5. `forward` - • if contract succeeded → return type validated LLM object - • else → graceful fallback answer - """ - - # ───────────────────────── init ───────────────────────── # - def __init__(self, min_coverage: float = 0.55, *args, **kwargs): - super().__init__(*args, **kwargs) - self.min_coverage = min_coverage # threshold for `post` - self.interaction_log: list[dict] = [] # keeps a history of queries - - # ───────────────────────── prompt ─────────────────────── # - @property - def prompt(self) -> str: - """ - A *static* description of what the LLM must do. - Braces {{like_this}} will be replaced with fields from - the object produced by `_validate_input`/`_act`. - """ - return ( - "You are an expert research assistant.\n" - "Given a QUESTION and a set of RELEVANT_SENTENCES, write a concise " - "answer. Cite every passage you use exactly as `(Doc )`. " - "Respond with a JSON object that fits the AnswerWithEvidence schema." - ) - - # ───────────────────────── pre ────────────────────────── # - def pre(self, input: MultiDocQAInput) -> bool: - """ - Guard-clauses before we even *touch* the LLM. - Raise ValueError with human-readable messages – they become corrective - prompts if `pre_remedy=True`. - """ - if not input.query.strip(): - raise ValueError("The query must not be empty.") - if not input.documents: - raise ValueError("You must supply at least one document.") - return True # all good - - # ───────────────────────── act ────────────────────────── # - def act(self, input: MultiDocQAInput, **kwargs) -> IntermediateRetrieved: - """ - Lightweight pseudo-retrieval. - - Steps: - • score each doc by term overlap with the query - • keep top-k (k ≤ 3) - • within each, take two most overlapping sentences - • log the interaction for later analytics - """ - k = min(3, len(input.documents)) - query_terms = {t.lower() for t in input.query.split()} - - # Score documents by *crude* term overlap - scored_docs = [] - for doc in input.documents: - overlap = sum(t in query_terms for t in doc.content.lower().split()) - scored_docs.append((overlap, doc)) - scored_docs.sort(reverse=True, key=lambda x: x[0]) - - top_docs = [doc for _, doc in scored_docs[:k]] - - # Extract at most 2 high-overlap sentences from each top doc - selected_sentences: list[str] = [] - for doc in top_docs: - sentences = [s.strip() for s in doc.content.split(".") if s.strip()] - sentences.sort( - reverse=True, - key=lambda s: sum(t in query_terms for t in s.lower().split()), - ) - selected_sentences.extend(sentences[:2]) - - # Record what we did (just for analytics / debugging) - self.interaction_log.append( - { - "query": input.query, - "num_docs": len(input.documents), - "top_doc_ids": [d.id for d in top_docs], - } - ) - - # Return a *different* LLMDataModel; this becomes the - # `current_input` for the output-validation phase. - return IntermediateRetrieved( - query=input.query, - top_docs=top_docs, - selected_sentences=selected_sentences, - target_snippet_count=input.max_snippets or 3, - ) - - # ───────────────────────── post ───────────────────────── # - def post(self, output: AnswerWithEvidence) -> bool: - """ - Semantic guarantees: - • non-empty answer - • coverage ≥ threshold - • high-coverage → must actually cite evidence - • evidence list ≤ `target_snippet_count` learned in `act` - Any violation ⇒ raise ValueError (triggers post-remedy or failure). - """ - if not output.answer.strip(): - raise ValueError("Answer text is empty.") - - # coverage gate - if output.coverage_score < self.min_coverage: - raise ValueError( - f"Coverage score {output.coverage_score:.2f} " - f"is below the minimum {self.min_coverage:.2f}." - ) - - # If it claims high coverage but provides no evidence, that's fishy - if output.coverage_score >= 0.8 and not output.evidence: - raise ValueError( - "High coverage claims require at least one evidence snippet." - ) - - # Enforce caller’s snippet bound (act stored it on self._current_input) - max_allowed = getattr(self, "_current_input", None) - if ( - isinstance(max_allowed, IntermediateRetrieved) - and output.evidence - and len(output.evidence) > max_allowed.target_snippet_count - ): - raise ValueError( - f"Too many snippets ({len(output.evidence)}), " - f"maximum allowed is {max_allowed.target_snippet_count}." - ) - - return True # all checks passed - - # ───────────────────────── forward ────────────────────── # - def forward(self, input: MultiDocQAInput, **kwargs) -> AnswerWithEvidence: - """ - ALWAYS executed (even if contract failed). - - Success path → return the LLM-validated object (`self.contract_result`) - Failure path → build a polite fallback answer that still matches schema - """ - # ── happy path ─────────────────────────────────────── # - if self.contract_successful and self.contract_result: - return self.contract_result - - # ── fallback (contract failed) ─────────────────────── # - first_doc = input.documents[0] - first_sentence = first_doc.content.split(".")[0][:300] # keep it short - return AnswerWithEvidence( - answer=( - "I’m not confident enough to answer precisely. " - "Please re-phrase the question or provide more documents." - ), - evidence=[DocSnippet(doc_id=first_doc.id, snippet=first_sentence)], - coverage_score=0.0, - ) - -if __name__ == "__main__": - # ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ - # 3. Mini-demo (only executed when you run the file directly) ▬ - # ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ - # ── tiny “corpus” ─────────────────────────────────────── # - docs = [ - Document( - id="A1", - content=( - "Symbolic AI combines formal logic with modern machine learning. " - "It allows transparent reasoning and explicit knowledge " - "representation while still benefiting from statistical models." - ), - ), - Document( - id="B2", - content=( - "Vector databases store embeddings of documents. They let users " - "quickly retrieve text that is semantically similar to a query " - "vector, enabling high-quality semantic search." - ), - ), - Document( - id="C3", - content=( - "Hybrid search merges sparse keyword techniques and dense vector " - "similarity, improving recall and precision, especially for " - "domain-specific collections." - ), - ), - ] - - # ── create agent instance ─────────────────────────────── # - agent = MultiDocQAgent(min_coverage=0.6) - - # ── ask a question ────────────────────────────────────── # - question = "Why are vector databases useful for semantic search?" - result = agent( - input=MultiDocQAInput( - query=question, - documents=docs, - max_snippets=2, # caller sets stricter evidence limit - ) - ) - - # ── result ───────────────────────––––––––––––––––––––––– # - print("\nAnswer:\n", result.answer) - print("\nCoverage:", result.coverage_score) - print("\nEvidence:") - for ev in result.evidence: - print(f" • (Doc {ev.doc_id}) {ev.snippet}") - - agent.contract_perf_stats(); -``` diff --git a/symbolicai-main/symbolicai-main/docs/source/FEATURES/error_handling.md b/symbolicai-main/symbolicai-main/docs/source/FEATURES/error_handling.md deleted file mode 100644 index 21463ecdd1cb8ec1371b195604fa0b0f97680d46..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/FEATURES/error_handling.md +++ /dev/null @@ -1,99 +0,0 @@ -# ❌ Error Handling and Debugging - ---- - -## ⚠️ Outdated or Deprecated Documentation ⚠️ -This documentation is outdated and may not reflect the current state of the SymbolicAI library. This page might be revived or deleted entirely as we continue our development. We recommend using more modern tools that infer the documentation from the code itself, such as [DeepWiki](https://deepwiki.com/ExtensityAI/symbolicai). This will ensure you have the most accurate and up-to-date information and give you a better picture of the current state of the library. - ---- - -A key idea of the SymbolicAI API is code generation, which may result in errors that need to be handled contextually. In the future, we want our API to self-extend and resolve issues automatically. We propose the `Try` expression, which has built-in fallback statements and retries an execution with dedicated error analysis and correction. The expression analyzes the input and error, conditioning itself to resolve the error by manipulating the original code. If the fallback expression succeeds, the result is returned. Otherwise, this process is repeated for the specified number of `retries`. If the maximum number of retries is reached and the problem remains unresolved, the error is raised again. - -Suppose we have some executable code generated previously. By the nature of generative processes, syntax errors may occur. Using the `Execute` expression, we can evaluate our generated code, which takes in a symbol and tries to execute it. Naturally, this will fail. However, in the following example, the `Try` expression resolves the syntax error, and we receive a computed and corrected result. - -```python -expr = Try(expr=Execute()) -sym = Symbol('a = int("3,")') # Some code with a syntax error -res = expr(sym) -print(res) # Output: a = 3 -``` - -We are aware that not all errors are as simple as the syntax error example shown, which can be resolved automatically. Many errors occur due to semantic misconceptions, requiring contextual information. We are exploring more sophisticated error handling mechanisms, including the use of streams and clustering to resolve errors in a hierarchical, contextual manner. It is also important to note that neural computation engines need further improvements to better detect and resolve errors. - -## 🕷️ Interpretability, Testing & Debugging - -Perhaps one of the most significant advantages of using neuro-symbolic programming is that it allows for a clear understanding of how well our LLMs comprehend simple operations. Specifically, we gain insight into whether and at what point they fail, enabling us to follow their StackTraces and pinpoint the failure points. In our case, neuro-symbolic programming enables us to debug the model predictions based on dedicated unit tests for simple operations. To detect conceptual misalignments, we can use a chain of neuro-symbolic operations and validate the generative process. Although not a perfect solution, as the verification might also be error-prone, it provides a principled way to detect conceptual flaws and biases in our LLMs. - -### Unit Testing Models - -Since our approach is to divide and conquer complex problems, we can create conceptual unit tests and target very specific and tractable sub-problems. The resulting measure, i.e., the success rate of the model prediction, can then be used to evaluate their performance and hint at undesired flaws or biases. - -This method allows us to design domain-specific benchmarks and examine how well general learners, such as GPT-3, adapt with certain prompts to a set of tasks. - -For example, we can write a fuzzy comparison operation that can take in digits and strings alike and perform a semantic comparison. LLMs can then be asked to evaluate these expressions. Often, these LLMs still fail to understand the semantic equivalence of tokens in digits vs. strings and provide incorrect answers. - -The following code snippet shows a unit test to perform semantic comparison of numbers (between digits and strings): - -```python -import unittest -from symai import * - -class TestComposition(unittest.TestCase): - def test_compare(self): - res = Symbol(10) > Symbol(5) - self.assertTrue(res) - res = Symbol(1) < Symbol('five') - self.assertTrue(res) - ... -``` - -### 🔥Debugging - -When creating complex expressions, we debug them by using the `Trace` expression, which allows us to print out the applied expressions and follow the StackTrace of the neuro-symbolic operations. Combined with the `Log` expression, which creates a dump of all prompts and results to a log file, we can analyze where our models potentially failed. - -#### Example: News Summary - -In the following example, we create a news summary expression that crawls the given URL and streams the site content through multiple expressions. The outcome is a news website created based on the crawled content. The `Trace` expression allows us to follow the StackTrace of the operations and observe which operations are currently being executed. If we open the `outputs/engine.log` file, we can see the dumped traces with all the prompts and results. - -```python -# crawling the website and creating a website based on its facts -news = News(url='https://www.cnbc.com/cybersecurity/', - pattern='cnbc', - filters=ExcludeFilter('sentences about subscriptions, licensing, newsletter'), - render=True) -expr = Log(Trace(news)) -res = expr() -``` - -See {doc}`here <../TUTORIALS/context>` for more information and full news summary code. - -Here is the corresponding StackTrace of the model: - - - -## 📈 Interface for Query and Response Inspection - -SymbolicAI is a data-driven framework by design. This implies that we can gather data from API interactions while delivering the requested responses. For rapid, dynamic adaptations or prototyping, we can swiftly integrate user-desired behavior into existing prompts. Moreover, we can log user queries and model predictions to make them accessible for post-processing. Consequently, we can enhance and tailor the model's responses based on real-world data. - -In the example below, we demonstrate how to use an `Output` expression to pass a handler function and access the model's input prompts and predictions. These can be utilized for data collection and subsequent fine-tuning stages. The handler function supplies a dictionary and presents keys for `input` and `output` values. The content can then be sent to a data pipeline for additional processing. - -```python -sym = Symbol('Hello World!') -def handler(res): - input_ = res['input'] - output = res['output'] -expr = Output(expr=sym.translate, - handler=handler, - verbose=True) -res = expr('German') -``` - -Since we used verbose, the console print of the `Output` expression is also visible: - -```bash -Input: (['Translate the following text into German:\n\nHello World!'],) -Expression: (value=Hello World!)> -args: ('German',) kwargs: {'input_handler': .input_handler at ... -Dictionary: {'instance': (value=None), 'func': ._func at ... -Output: Hallo Welt! -``` diff --git a/symbolicai-main/symbolicai-main/docs/source/FEATURES/expressions.md b/symbolicai-main/symbolicai-main/docs/source/FEATURES/expressions.md deleted file mode 100644 index ed9aaf218eeb4e11b92dea4d570baa98e37914cb..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/FEATURES/expressions.md +++ /dev/null @@ -1,82 +0,0 @@ -# Expressions - ---- - -## ⚠️ Outdated or Deprecated Documentation ⚠️ -This documentation is outdated and may not reflect the current state of the SymbolicAI library. This page might be revived or deleted entirely as we continue our development. We recommend using more modern tools that infer the documentation from the code itself, such as [DeepWiki](https://deepwiki.com/ExtensityAI/symbolicai). This will ensure you have the most accurate and up-to-date information and give you a better picture of the current state of the library. - ---- - -## Overview -An `Expression` is a non-terminal symbol that can be further evaluated. It inherits all the properties from the Symbol class and overrides the `__call__` method to evaluate its expressions or values. All other expressions are derived from the `Expression` class, which also adds additional capabilities, such as the ability to `fetch` data from URLs, `search` on the internet, or `open` files. These operations are specifically separated from the `Symbol` class as they do not use the `value` attribute of the Symbol class. - -## Expression Design -SymbolicAI's API closely follows best practices and ideas from `PyTorch`, allowing the creation of complex expressions by combining multiple expressions as a computational graph. Each Expression has its own `forward` method that needs to be overridden. The `forward` method is used to define the behavior of the expression. It is called by the `__call__` method, which is inherited from the `Expression` base class. The `__call__` method evaluates an expression and returns the result from the implemented `forward` method. This design pattern evaluates expressions in a lazy manner, meaning the expression is only evaluated when its result is needed. It is an essential feature that allows us to chain complex expressions together. Numerous helpful expressions can be imported from the `symai.components` file. - -## Core Properties -Other important properties inherited from the Symbol class include `sym_return_type` and `static_context`. These two properties define the context in which the current Expression operates, as described in the [Prompt Design](operations.md#prompt-design) section. The `static_context` influences all operations of the current Expression sub-class. The `sym_return_type` ensures that after evaluating an Expression, we obtain the desired return object type. It is usually implemented to return the current type but can be set to return a different type. - -## Expression Structure -Expressions may have more complex structures and can be further sub-classed, as shown in the `Sequence` expression example in the following figure: - - - -A Sequence expression can hold multiple expressions evaluated at runtime. - -## Expression Types - -### Sequence Expressions -Here is an example of defining a Sequence expression: - -```python -# First import all expressions -from symai.components import * -# Define a sequence of expressions -Sequence( - Clean(), - Translate(), - Outline(), - Compose('Compose news:'), -) -``` - -### Stream expressions - -As previously mentioned, we can create contextualized prompts to define the behavior of operations on our neural engine. However, this limits the available context size due to GPT-3 Davinci's context length constraint of 4097 tokens. This issue can be addressed using the `Stream` processing expression, which opens a data stream and performs chunk-based operations on the input stream. - -A Stream expression can be wrapped around other expressions. For example, the chunks can be processed with a `Sequence` expression that allows multiple chained operations in a sequential manner. Here is an example of defining a Stream expression: - -```python -Stream(Sequence( - Clean(), - Translate(), - Outline(), - Embed() -)) -``` - -The example above opens a stream, passes a `Sequence` object which cleans, translates, outlines, and embeds the input. Internally, the stream operation estimates the available model context size and breaks the long input text into smaller chunks, which are passed to the inner expression. The returned object type is a `generator`. - -This approach has the drawback of processing chunks independently, meaning there is no shared context or information among chunks. To address this issue, the `Cluster` expression can be used, where the independent chunks are merged based on their similarity, as illustrated in the following figure: - - - -In the illustrated example, all individual chunks are merged by clustering the information within each chunk. It consolidates contextually related information, merging them meaningfully. The clustered information can then be labeled by streaming through the content of each cluster and extracting the most relevant labels, providing interpretable node summaries. - -The full example is shown below: - -```python -stream = Stream(Sequence( - Clean(), - Translate(), - Outline(), -)) -sym = Symbol('') -res = Symbol(list(stream(sym))) -expr = Cluster() -expr(res) -``` - -Next, we could recursively repeat this process on each summary node, building a hierarchical clustering structure. Since each Node resembles a summarized subset of the original information, we can use the summary as an index. The resulting tree can then be used to navigate and retrieve the original information, transforming the large data stream problem into a search problem. - -Alternatively, vector-based similarity search can be used to find similar nodes. Libraries such as [Annoy](https://github.com/spotify/annoy), [Faiss](https://github.com/facebookresearch/faiss), or [Milvus](https://github.com/milvus-io/milvus) can be employed for searching in a vector space. diff --git a/symbolicai-main/symbolicai-main/docs/source/FEATURES/import.md b/symbolicai-main/symbolicai-main/docs/source/FEATURES/import.md deleted file mode 100644 index b04e85a890e212f54deb0e54619a9fd1ee6e7620..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/FEATURES/import.md +++ /dev/null @@ -1,101 +0,0 @@ -# Module Management - -The `Import` class is a module management class in the SymbolicAI library. This class provides an easy and controlled way to manage the use of external modules in the user’s project, with main functions including the ability to install, uninstall, update, and check installed modules. It is used to manage expression loading from packages and accesses the respective metadata from the `package.json`. - -The metadata for the package includes version, name, description, and expressions. It also lists the package dependencies required by the package. - -Here is an example of a `package.json` file: - -```json -{ - "version": "0.0.1", - "name": "/", - "description": "", - "expressions": [{"module": "src/func", "type": "MyExpression"}], - "run": {"module": "src/func", "type": "MyExpression"}, - "dependencies": [] -} -``` - -- `version`: Specifies the version number of the package. It is recommended to follow semantic versioning. -- `name`: Specifies the name of the package. It typically follows the format `/`, where `` is your GitHub username and `` is the name of your package repository. -- `description`: Provides a brief description of the package. -- `expressions`: Defines the exported expressions for the package. Each expression is defined by its `module` and `type`. The `module` specifies the file path or module name where the expression is defined, and the `type` specifies the type of the expression. These are used to be accessed from code by calling `Import. -- `run`: Specifies the expression that should be executed when the package is run. It follows the same format as the `expressions` property, only defined by a single entry point type. -- `dependencies`: Lists the package dependencies to other SymbolicAI packages! Dependencies can be specified with their package name `/`. -## Working with Local Packages - -The `Import` class supports both GitHub-hosted packages and local packages: - -1. **Direct Local Imports**: You can directly import a package from a local directory by providing the full path: - ```python - local_module = Import("/path/to/local/module") - ``` - -2. **Named Local Imports**: You can import a local package but register it with a specific name: - ```python - Import.install("username/repo_name", local_path="/path/to/local/module") - ``` - -When working with local packages, the system will still look for a valid `package.json` file in the package root directory. - -Note that the `package.json` file is automatically created when you use the Package Initializer tool (`symdev`) to create a new package. Alongside the `package.json` also a `requirements.txt` is created. This file contains all the `pip` relevant dependencies. - -To import a package from code, see the following example: - -```python -from symai import Import -symask_module = Import("ExtensityAI/symask") -``` -You can also pass additional parameters to control installation behavior: - -```python -# Install a module with Git submodules initialized -symask_module = Import("ExtensityAI/symask", submodules=True) - -# Import from a local directory -local_module = Import("/path/to/local/module") - -# Import using a local path but install as a named package -named_local = Import("username/repo_name", local_path="/path/to/local/module") -``` - -This command will clone the module from the given GitHub repository (`ExtensityAI/symask` in this case), install any dependencies, and expose the module's classes for use in your project. - -You can also install a module without instantiating it using the `install` method: - -```python -# Basic installation -Import.install("ExtensityAI/symask") - -# Install with Git submodules -Import.install("ExtensityAI/symask", submodules=True) - -# Install from a local directory -Import.install("username/repo_name", local_path="/path/to/local/module") -``` - -The `Import` class will automatically handle the cloning of the repository and the installation of dependencies that are declared in the `package.json` and `requirements.txt` files of the repository. -You can also update an installed package using the `update` method: - -```python -# Basic update -Import.update("ExtensityAI/symask") - -# Update including Git submodules -Import.update("ExtensityAI/symask", submodules=True) -``` - -Similarly, you can remove a package: - -```python -Import.remove("ExtensityAI/symask") -``` - -Or list all installed packages: - -```python -installed_packages = Import.list_installed() -``` - -Please refer to the comments in the code for more detailed explanations of how each method of the `Import` class works. \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/docs/source/FEATURES/operations.md b/symbolicai-main/symbolicai-main/docs/source/FEATURES/operations.md deleted file mode 100644 index e21232c772d07dede00a75cbb31649b08d87299f..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/FEATURES/operations.md +++ /dev/null @@ -1,166 +0,0 @@ -# Operations - ---- - -## ⚠️ Outdated or Deprecated Documentation ⚠️ -This documentation is outdated and may not reflect the current state of the SymbolicAI library. This page might be revived or deleted entirely as we continue our development. We recommend using more modern tools that infer the documentation from the code itself, such as [DeepWiki](https://deepwiki.com/ExtensityAI/symbolicai). This will ensure you have the most accurate and up-to-date information and give you a better picture of the current state of the library. - ---- - -## Overview -Operations form the core of our framework and serve as the building blocks of our API. These operations define the behavior of symbols by acting as contextualized functions that accept a `Symbol` object and send it to the neuro-symbolic engine for evaluation. Operations then return one or multiple new objects, which primarily consist of new symbols but may include other types as well. Polymorphism plays a crucial role in operations, allowing them to be applied to various data types such as strings, integers, floats, and lists, with different behaviors based on the object instance. - -Operations are executed using the `Symbol` object's `value` attribute, which contains the original data type converted into a string representation and sent to the engine for processing. As a result, all values are represented as strings, requiring custom objects to define a suitable `__str__` method for conversion while preserving the object's semantics. - -Inheritance is another essential aspect of our API, which is built on the `Symbol` class as its base. All operations are inherited from this class, offering an easy way to add custom operations by subclassing `Symbol` while maintaining access to basic operations without complicated syntax or redundant functionality. Subclassing the `Symbol` class allows for the creation of contextualized operations with unique constraints and prompt designs by simply overriding the relevant methods. However, it is recommended to subclass the `Expression` class for additional functionality. - -Defining custom operations can be done through overriding existing Python methods and providing a custom prompt object with example code. Here is an example of creating a custom `==` operation by overriding the `__eq__` method: - -```python -class Demo(ai.Symbol): - def __eq__(self, other) -> bool: - @ai.equals(examples=ai.Prompt([ - "1 == 'ONE' =>True", - "'six' == 7 =>False", - "'Acht' == 'eight' =>True", - ... - ]) - ) - def _func(_, other) -> bool: - return False # default behavior on failure - return _func(self, other) -``` - -## Basic Implementation - -Basic operations in `Symbol` are implemented by defining local functions and decorating them with corresponding operation decorators from the `symai/core.py` file, a collection of predefined operation decorators that can be applied rapidly to any function. Using local functions instead of decorating main methods directly avoids unnecessary communication with the neural engine and allows for default behavior implementation. It also helps cast operation return types to symbols or derived classes, using the `self.sym_return_type(...)` method for contextualized behavior based on the determined return type. More details can be found in the [`Symbol` class](https://github.com/ExtensityAI/symbolicai/blob/main/symai/symbol.py). - -The following section demonstrates that most operations in `symai/core.py` are derived from the more general `few_shot` decorator. - -## Operation Types - -### {#custom-operations} Custom Operations - -Defining custom operations is also possible, such as creating an operation to generate a random integer between 0 and 10: - -```python -class Demo(ai.Expression): - @ai.zero_shot(prompt="Generate a random integer between 0 and 10.", - constraints=[ - lambda x: x >= 0, - lambda x: x <= 10 - ]) - def get_random_int(self) -> int: - pass - -demo = Demo() -random_int = demo.get_random_int() -print(random_int) # Output: A random integer between 0 and 10 -``` - -The Symbolic API employs Python `Decorators` to define operations, utilizing the `@ai.zero_shot` decorator to create custom operations that do not require demonstration examples when the prompt is self-explanatory. In this example, the `zero_shot` decorator accepts two arguments: `prompt` and `constraints`. The former defines the prompt dictating the desired operation behavior, while the latter establishes validation constraints for the computed outcome, ensuring it meets expectations. - -If a constraint is not satisfied, the implementation will utilize the specified `default` fallback or default value. If neither is provided, the Symbolic API will raise a `ConstraintViolationException`. The return type is set to `int` in this example, so the value from the wrapped function will be of type int. The implementation uses auto-casting to a user-specified return data type, and if casting fails, the Symbolic API will raise a `ValueError`. If no return type is specified, the return type defaults to `Any`. - -### Few-Shot Operations - -The `@ai.few_shot` decorator is a generalized version of the `@ai.zero_shot` decorator, used to define custom operations that require demonstration examples. To provide a clearer understanding, we present the function signature of the `few_shot` decorator: - -```python -def few_shot(prompt: str, - examples: Prompt, - constraints: List[Callable] = [], - default: Optional[object] = None, - limit: int = 1, - pre_processors: Optional[List[PreProcessor]] = None, - post_processors: Optional[List[PostProcessor]] = None, - **decorator_kwargs): -``` - -The `prompt` and `constraints` attributes behave similarly to those in the `zero_shot` decorator. The `examples` and `limit` arguments are new. The `examples` argument defines a list of demonstrations used to condition the neural computation engine, while the `limit` argument specifies the maximum number of examples returned, given that there are more results. The `pre_processors` argument accepts a list of `PreProcessor` objects for pre-processing input before it's fed into the neural computation engine. The `post_processors` argument accepts a list of `PostProcessor` objects for post-processing output before returning it to the user. Lastly, the `decorator_kwargs` argument passes additional arguments from the decorator kwargs, which are streamlined towards the neural computation engine and other engines. - -To provide a more comprehensive understanding of our conceptual implementation, refer to the flow diagram below, containing the most important classes: - - - -The colors indicate logical groups of data processing steps. `Yellow` represents input and output data, `blue` shows places where one can customize or prepare the input of the engine, `green` indicates post-processing steps of the engine response, `red` displays the application of constraints (including attempted casting of the `return type signature` if specified in the decorated method), and `grey` denotes the custom method defining all properties, thus having access to all the previously mentioned objects. - -To conclude this section, here is an example of how to write a custom Japanese name generator using our `@ai.zero_shot` decorator: - -```python -import symai as ai -class Demo(ai.Symbol): - @ai.few_shot(prompt="Generate Japanese names: ", - examples=ai.Prompt( - ["愛子", "和花", "一郎", "和枝"] - ), - limit=2, - constraints=[lambda x: len(x) > 1]) - def generate_japanese_names(self) -> list: - return ['愛子', '和花'] # dummy implementation -``` - -If the neural computation engine cannot compute the desired outcome, it will revert to the `default` implementation or default value. If no default implementation or value is found, the method call will raise an exception. - -## Prompt Design - -The `Prompt` class is used to perform all the above operations. Acting as a container for information required to define a specific operation, the `Prompt` class also serves as the base class for all other Prompt classes. - -Here's an example of defining a `Prompt` to enforce the neural computation engine to compare two values: - -```python -class CompareValues(ai.Prompt): - def __init__(self) -> ai.Prompt: - super().__init__([ - "4 > 88 =>False", - "-inf < 0 =>True", - "inf > 0 =>True", - "4 > 3 =>True", - "1 < 'four' =>True", - ... - ]) -``` - -When calling the `<=` operation on two Symbols, the neural computation engine evaluates the symbols in the context of the `CompareValues` prompt. - -```python -res = ai.Symbol(1) <= ai.Symbol('one') -``` - -This statement evaluates to `True` since the fuzzy compare operation conditions the engine to compare the two Symbols based on their semantic meaning. - -```bash -:[Output]: -True -``` - -In general, the semantics of Symbol operations may vary depending on the context hierarchy of the expression class and the operations used. To better illustrate this, we display our conceptual prompt design in the following figure: - - - -The figure illustrates the hierarchical prompt design as a container for information provided to the neural computation engine to define a task-specific operation. The `yellow` and `green` highlighted boxes indicate mandatory string placements, dashed boxes represent optional placeholders, and the `red` box marks the starting point of model prediction. - -Three main prompt designs are considered: `Context-based Prompts`, `Operational Prompts`, and `Templates`. Prompts can be curated either by inheritance or composition. For example, `Static Context` can be defined by inheriting the `Expression` class and overriding the `static_context` property. An `Operation` and `Template` prompt can be created by providing a `PreProcessor` to modify input data. - -Each prompt concept is explained in more detail below: - -- `Context-based Prompts (Static, Dynamic, and Payload)` are considered optional and can be defined either statically (by subclassing the Expression class and overriding the `static_context` property) or at runtime (by updating the `dynamic_context` property or passing `payload` kwargs to a method). As an example of using the `payload` kwargs via method signature: - - ```python - # creating a query to ask if an issue was resolved or not - sym = Symbol("") - q = sym.query("Was the issue resolved?") - # write manual condition to check if the issue was resolved - if 'not resolved' in q: - # do a new query but payload the previous query answer to the new query - sym.query("What was the resolution?", payload=q) - ... - else: - pass # all good - ``` - - Regardless of how the context is set, the contextualized prompt defines the desired behavior of Expression operations. For example, one can operate within a domain-specific language context without having to override each base class method. See more details [here](https://extensityai.gitbook.io/symbolicai/tutorials/data_query). - -- `Operation` prompts define the behavior of atomic operations and are mandatory to express the nature of such operations. For example, the `+` operation is used to add two Symbols together, so its prompt explains this behavior. `Examples` provide an optional structure giving the neural computation engine a set of demonstrations used to condition it properly. For instance, the `+` operation prompt can be conditioned on adding numbers by providing demonstrations like `1 + 1 = 2`, `2 + 2 = 4`, etc. - -- `Template` prompts are optional and encapsulate the resulting prediction to enforce a specific format. For example, to generate HTML tags, one can use the curated `{{placeholder}}` template. This template ensures that the neural computation engine starts the generation process within the context of an HTML tag format, avoiding the production of irrelevant descriptions regarding its task. diff --git a/symbolicai-main/symbolicai-main/docs/source/FEATURES/primitives.md b/symbolicai-main/symbolicai-main/docs/source/FEATURES/primitives.md deleted file mode 100644 index e5688ead96d0c65c4df2cc3e49662e3cb1f136a4..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/FEATURES/primitives.md +++ /dev/null @@ -1,1321 +0,0 @@ -# Primitives Cheat-Sheet - -> _Primitives are the atoms of the SymbolicAI API – small, orthogonal operations that can be freely combined to express very rich behaviour. -Every `Symbol` automatically inherits them, so there is no import-gymnastics required: just create a symbol and start hacking._ - -This page gives you a **hands-on overview** of the most useful primitives that ship with -`symai`. All examples are *copy-pastable* – open a Python REPL and play with them! The table of -contents below mirrors the internal organisation of `symai/ops/primitives.py`, so if you ever need -more detail you know where to look. - -> ❗️**NOTE**❗️We will focus mostly on the **semantic** behaviour of the primitives, but you can also use them in **syntactic** mode, which is the default. -Syntactic mode behaves like a normal Python value, unless otherwise specified. -Be sure to check the examples below to see how the primitives behave. - - -## Supported Primitives - SymbolicAI -This table summarizes all supported primitives, grouped by category. Use Python operators in -either syntactic (`Symbol(...).syn` or `Symbol(...)`) or semantic (`Symbol(...).sem` or `Symbol(..., semantic=True)`) mode. Semantic mode invokes neuro-symbolic reasoning. -**Checkmark** columns show which mode is supported; description explains the behavior. - -| Primitive/Operator | Category | Syntactic | Semantic | Description | -|--------------------|-----------------|:---------:|:--------:|-------------| -| `.sem` / `.syn` | Casting | ✓ | ✓ | Switches a symbol between syntactic (literal) and semantic (neuro-symbolic) behavior. | -| `==` | Comparison | ✓ | ✓ | Tests for equality. Syntactic: literal match. Semantic: fuzzy/conceptual equivalence (e.g. 'Hi' == 'Hello'). | -| `!=` | Comparison | ✓ | ✓ | Tests for inequality. Syntactic: literal not equal. Semantic: non-equivalence or opposite concepts. | -| `>` | Comparison | ✓ | ✓ | Greater-than. Syntactic: numeric/string compare. Semantic: abstract comparison (e.g. 'hot' > 'warm'). | -| `<` | Comparison | ✓ | ✓ | Less-than. Syntactic: numeric/string compare. Semantic: abstract ordering (e.g. 'cat' < 'dog'). | -| `>=` | Comparison | ✓ | ✓ | Greater or equal. Syntactic or conceptual. | -| `<=` | Comparison | ✓ | ✓ | Less or equal. Syntactic or conceptual. | -| `in` | Membership | ✓ | ✓ | Syntactic: element in list/string. Semantic: membership by meaning (e.g. 'fruit' in ['apple', ...]). | -| `~` | Invert | ✓ | ✓ | Negation: Syntactic: logical NOT/bitwise invert. Semantic: conceptual inversion (e.g. 'True' ➔ 'False', 'I am happy.' ➔ 'Happiness is me.'). | -| `+` | Arithmetic | ✓ | ✓ | Syntactic: numeric/string/list addition. Semantic: meaningful composition, blending, or conceptual merge. | -| `-` | Arithmetic | ✓ | ✓ | Syntactic: subtraction/negate. Semantic: replacement or conceptual opposition. | -| `*` | Arithmetic | ✓ | | Syntactic: multiplication/repeat. Semantic: expand or strengthen meaning. | -| `@` | Arithmetic | ✓ | | Sytactic: string concatenation. | -| `/` | Arithmetic | ✓ | | Syntactic: division. On strings, it splits the string based on delimiter (e.g. `Symbol('a b') / ' '` -> `['a', 'b']`))). | -| `//` | Arithmetic | ✓ | | Floor division. | -| `%` | Arithmetic | ✓ | | Modulo. Semantic: find remainder or part, can be used creatively over concepts. | -| `**` | Arithmetic | ✓ | | Power operation. Semantic: (hypernym or intensifier, depending on domain). | -| `&` | Logical/Bitwise | ✓ | ✓ | Syntactic: bitwise/logical AND. Semantic: logical conjunction, inference, e.g., context merge. | -| `\|` | Logical/Bitwise | ✓ | ✓ | Syntactic: bitwise/logical OR. Semantic: conceptual alternative/option. | -| `^` | Logical/Bitwise | ✓ | ✓ | Syntactic: bitwise XOR. Semantic: exclusive option/concept distinction. | -| `<<` | Shift | ✓ | ✓ | Syntactic: left-shift (integers). Semantic: prepend or rearrange meaning/order. | -| `>>` | Shift | ✓ | ✓ | Syntactic: right-shift (integers). Semantic: append or rearrange meaning/order. | -| `+=`, `-=`, `*=`, `/=`, `//=`, `%=`, `**=` | In-place Arithmetic | ✓ | ✓ | In-place enhanced assignment, some syntactic and some semantic (see above). | -| `&=`, `\|=`, `^=` | In-place Logical| ✓ | ✓ | In-place enhanced bitwise/logical assignment, both syntactic and semantic. | -| `.cast(type)`, `.to(type)` | Casting | ✓ | | Cast to a specified type (e.g., int, float, str). | -| `.str()`, `.int()`, `.float()`, `.bool()` | Casting | ✓ | | Cast to basic types. | -| `.ast()` | Casting | ✓ | | Parse a Python literal string into a native object. | -| `symbol[index]`, `symbol[start:stop]` | Iteration | ✓ | ✓ | Get item or slice (list, tuple, dict, numpy array). | -| `symbol[index] = value` | Iteration | ✓ | ✓ | Set item or slice. | -| `del symbol[index]` | Iteration | ✓ | ✓ | Delete item or key. | -| `.split(delimiter)` | String Helper | ✓ | | Split a string or sequence into a list. | -| `.join(delimiter)` | String Helper | ✓ | | Join a list of strings into a string. | -| `.startswith(prefix)` | String Helper | ✓ | ✓ | Check if a string starts with given prefix (in both modes). | -| `.endswith(suffix)` | String Helper | ✓ | ✓ | Check if a string ends with given suffix (in both modes). | -| `.equals(string, context?)` | Comparison | | ✓ | Semantic/contextual equality beyond `==`. | -| `.contains(element)` | Comparison | | ✓ | Semantic contains beyond `in`. | -| `.isinstanceof(query)` | Comparison | | ✓ | Semantic type checking. | -| `.interpret(prompt, accumulate?)`| Expression Handling | | ✓ | Interpret prompts/expressions| -| `.get_results()` | Expression Handling | ✓ | | Retrieve accumulated interpretation results. | -| `.clear_results()` | Expression Handling | ✓ | | Clear accumulated interpretation results. | -| `.clean()` | Data Handling | | ✓ | Clean text (remove extra whitespace, newlines, tabs). | -| `.summarize(context?)` | Data Handling | | ✓ | Summarize text (optionally with context). | -| `.outline()` | Data Handling | | ✓ | Generate outline from structured text. | -| `.filter(criteria, include?)` | Data Handling | | ✓ | Filter text by criteria (exclude/include). | -| `.map(instruction, prompt?)` | Data Handling | | ✓ | Semantic mapping over iterables. | -| `.modify(changes)` | Data Handling | | ✓ | Apply modifications according to prompt. | -| `.replace(old, new)` | Data Handling | | ✓ | Replace substrings in data. | -| `.remove(information)` | Data Handling | | ✓ | Remove specified text. | -| `.include(information)` | Data Handling | | ✓ | Include additional information. | -| `.combine(information)` | Data Handling | | ✓ | Combine with another text fragment. | -| `.unique(keys?)` | Uniqueness | | ✓ | Extract unique elements or entries. | -| `.compose()` | Uniqueness | | ✓ | Compose a coherent narrative. | -| `.rank(measure?, order?)` | Pattern Matching| | ✓ | Rank items by a given measure/order. | -| `.extract(pattern)` | Pattern Matching| | ✓ | Extract info matching a pattern. | -| `.correct(context, exception)` | Pattern Matching | | ✓ | Correct code/text based on prompt/exception. | -| `.translate(language)` | Pattern Matching | | ✓ | Translate text into another language. | -| `.choice(cases, default)` | Pattern Matching| | ✓ | Select best match from provided cases. | -| `.query(context, prompt?, examples?)` | Query Handling | | ✓ | Query structured data with a question or prompt. | -| `.convert(format)` | Query Handling | | ✓ | Convert data to specified format (YAML, XML, etc.). | -| `.transcribe(modify)` | Query Handling | | ✓ | Transcribe/reword text per instructions. | -| `.analyze(exception, query?)` | Execution Control | | ✓ | Analyze code execution and exceptions. | -| `.execute()`, `.fexecute()` | Execution Control | | ✓ | Execute code (with fallback). | -| `.simulate()` | Execution Control | | ✓ | Simulate code or process semantically. | -| `.sufficient(query)` | Execution Control | | ✓ | Check if information is sufficient. | -| `.list(condition)` | Execution Control | | ✓ | List items matching criteria. | -| `.foreach(condition, apply)`| Execution Control | | ✓ | Apply action to each element. | -| `.stream(expr, token_ratio)` | Execution Control | | ✓ | Stream-process large inputs. | -| `.ftry(expr, retries)` | Execution Control | | ✓ | Fault-tolerant execution with retries. | -| `.dict(context, **kwargs)` | Dict Handling | | ✓ | Convert text/list into a dict semantically. | -| `.template(template, placeholder?)` | Template Styling | ✓ | | Fill in placeholders in a template string. | -| `.style(description, libraries?)` | Template Styling | | ✓ | Style text/code (e.g., syntax highlighting). | -| `.cluster(**clustering_kwargs?)` | Data Clustering | | ✓ | Cluster data into groups semantically. (uses sklearn's DBSCAN)| -| `.embed()` | Embedding | | ✓ | Generate embeddings for text/data. | -| `.embedding` | Embedding | | ✓ | Retrieve embeddings as a numpy array. | -| `.similarity(other, metric?, normalize?)` | Embedding | | ✓ | Compute similarity between embeddings. | -| `.distance(other, kernel?)` | Embedding | | ✓ | Compute distance between embeddings. | -| `.zip()` | Embedding | | ✓ | Package id, embedding, query into tuples. | -| `.open(path?)` | IO Handling | ✓ | | Open a file and read its contents. | -| `.input(message?)` | IO Handling | ✓ | | Read user input interactively. | -| `.save(path, serialize?, replace?)` | Persistence | ✓ | | Save a symbol to file (pickle/text). | -| `.load(path)` | Persistence | ✓ | | Load a symbol from file. | -| `.expand()` | Persistence | | ✓ | Generate and attach code based on prompt. | -| `.output()` | Output Handling | ✓ | | Handle/capture output with handler. | - ---- -## 1. Syntactic **vs.** Semantic Symbols - -`Symbol` comes in **two flavours**: - -1. **Syntactic** – behaves like a normal Python value (string, list, int ‐ whatever you passed in). -2. **Semantic** – is wired to the neuro-symbolic engine and therefore *understands* meaning and - context. - -Why is syntactic the default? Because Python operators (`==`, `~`, `&`, …) are overloaded in -`symai`. If we would immediately fire the engine for *every* bitshift or comparison, code would be -slow and could produce surprising side-effects. Starting syntactic keeps things safe and fast; you -opt-in to semantics only where you need them. - -### How to switch to the semantic view - -1. **At creation time** - - ```python - from symai import Symbol - - s = Symbol("Cats are adorable", semantic=True) # already semantic - ``` - -2. **On demand with the `.sem` projection** – the twin `.syn` flips you back: - - ```python - s = Symbol("Cats are adorable") # default = syntactic - print(s.startswith("Cats")) # syntactic => True - print(s.sem.startswith("animal")) # semantic => True - print("feline" in s.sem) # semantic => True - result = (s / " ")[0] # syntactic operator split, syntactic index - print(result) # => 'Cats' - ``` - -Because the projections return the *same underlying object* with just a different behavioural -coat, you can weave complex chains of syntactic and semantic operations on a single symbol. - -## 2. Inversion and Negation - -#### Inversion (`~`) - -```python -s = Symbol("I am standing on the shoulders of giants.", semantic=True) -print(~s) # => Giants are standing on my shoulders. -``` - -#### Negation (`-`) - -```python -s = Symbol("I am happy.", semantic=True) -print(-s) # => I am not happy. -``` - -## 3. Comparison Operations - -### Equality (`==`) and Inequality (`!=`) - -The equality and inequality operators showcase one of the most powerful aspects of semantic symbols: **conceptual equivalence** rather than just literal matching. - -#### Semantic Equality - Conceptual Equivalence - -```python -from symai import Symbol - -# Semantic greeting comparison - understands meaning -greeting_sem = Symbol('Hello there!', semantic=True) -greeting_variant = 'Hi there!' - -print(greeting_sem == greeting_variant) # => True - -# Semantic farewell comparison -farewell_sem = Symbol('Goodbye friend!', semantic=True) -farewell_variant = 'See you later!' - -print(farewell_sem == farewell_variant) # => True - -# Works with lists too - semantic understanding -list_sem = Symbol([1, 2, 3], semantic=True) -list_different = Symbol([3, 2, 1]) - -print(list_sem == list_different) # => False -``` - -#### Semantic Inequality (`!=`) - -The inequality operator works as the logical inverse of equality with conceptual understanding: - -```python -# Semantic inequality - conceptual differences -greeting_sem = Symbol('Hello there!', semantic=True) -greeting_variant = 'Hi there!' - -print(greeting_sem != greeting_variant) # => False - -farewell_sem = Symbol('Goodbye friend!', semantic=True) -farewell_variant = 'See you later!' - -print(farewell_sem != farewell_variant) # => False -``` - -#### Advanced Contextual Equality - Custom Context Comparison - -Beyond basic semantic equality, symbols support **contextual comparison** where you can specify the context for evaluation: - -```python -from symai import Symbol - -# Contextual greeting comparison -greeting = Symbol('Hello, good morning!') -similar_greeting = 'Hi there, good day!' - -# Compare with specific greeting context -result = greeting.equals(similar_greeting, context='greeting context') -print(result) # => True - -# Compare with different contexts for nuanced evaluation -formal_greeting = Symbol('Good morning, sir.') -casual_greeting = 'Hey, what\'s up?' - -# Context-aware politeness comparison -politeness_comparison = formal_greeting.equals(casual_greeting, context='politeness level') -print(politeness_comparison) # => False -``` - -## 4. Membership Operations - -### The `in` Operator - Semantic Containment - -The `in` operator demonstrates how semantic symbols can understand **conceptual membership** beyond literal substring or element matching. - -#### Semantic Membership - Conceptual Containment - -```python -from symai import Symbol - -# Semantic string containment - understands concepts -str_sem = Symbol('apple banana cherry', semantic=True) -concept_search = 'fruit' - -print(concept_search in str_sem) # => True (understands apple/banana are fruits) - -# Semantic list containment - conceptual understanding -list_sem = Symbol(['apple', 'banana', 'cherry'], semantic=True) - -print(concept_search in list_sem) # => True (conceptual membership) - -# More examples of semantic containment -animals_sem = Symbol('cat dog bird fish', semantic=True) -print('pet' in animals_sem) # => True (cats and dogs are pets) -print('mammal' in animals_sem) # => True (cat and dog are mammals) -print('vehicle' in animals_sem) # => False (no vehicles in the list) -``` - -#### Enhanced Semantic Containment - Multi-Type Support - -The `contains()` method provides advanced semantic containment that works across different data types: - -```python -from symai import Symbol - -# Semantic containment in text with concept understanding -text = Symbol('The vehicle moved quickly down the road') -print(text.contains('car')) # => True (vehicle can semantically contain car) - -# Containment with mixed data types -mixed_data = Symbol([1, 'two', 3.0, True]) -print(mixed_data.contains('two')) # => True (exact string match) -print(mixed_data.contains(True)) # => True (exact boolean match) -``` - -## 5. Ordering and Comparison Operations - -### Greater Than (`>`) and Less Than (`<`) and Greater or Equal (`>=`) and Less or Equal (`<=`) - -Semantic symbols can understand abstract ordering and magnitude relationships beyond numeric comparisons. - -```python -from symai import Symbol - -# Semantic size comparison - understands relative magnitude -large_sem = Symbol('enormous', semantic=True) -small_sem = Symbol('tiny', semantic=True) - -print(large_sem > small_sem) # => True (enormous is conceptually larger than tiny) - -# Semantic animal size comparison -cat_sem = Symbol('cat', semantic=True) -dog_sem = Symbol('dog', semantic=True) - -print(cat_sem < dog_sem) # => True (dogs are generally larger than cats) - -# Temperature comparisons - semantic understanding of hot/cold -cold_sem = Symbol('freezing', semantic=True) -hot_sem = Symbol('scorching', semantic=True) - -print(cold_sem < hot_sem) # => True (freezing is less than scorching) - -# Semantic number understanding -word_number = Symbol('fifty', semantic=True) -regular_number = 45 - -print(word_number > regular_number) # => True (understands "fifty" means 50) - -# Speed comparisons with semantic understanding -fast_sem = Symbol('lightning speed', semantic=True) -slow_sem = Symbol('snail pace', semantic=True) - -print(fast_sem >= slow_sem) # => True (lightning speed is much faster) - -# Strength comparisons -weak_sem = Symbol('fragile', semantic=True) -strong_sem = Symbol('robust', semantic=True) - -print(weak_sem <= strong_sem) # => True (fragile is weaker than robust) -``` - -## 6. Shift Operations - Semantic Inclusion - -### Left Shift (`<<`) and Right Shift (`>>`) - -Shift operations perform **semantic inclusion** by incorporating one symbol's content into another. The direction of the operator indicates where the inclusion occurs - left shift (`<<`) prepends content, while right shift (`>>`) appends content. - -#### Semantic Inclusion Operations - -```python -from symai import Symbol - -# Left shift - prepend/include at the beginning -data_stream = Symbol('data stream', semantic=True) -left_direction = Symbol('left') -result = data_stream << left_direction -print(result) # => "left data stream" - -# Right shift - append/include at the end -info_flow = Symbol('information flow', semantic=True) -right_direction = Symbol('right') -result = info_flow >> right_direction -print(result) # => "information flow right" - -# Priority and urgency - prepend urgent to task -priority_task = Symbol('high priority task', semantic=True) -urgency = Symbol('urgent') -result = priority_task << urgency -print(result) # => "urgent high priority task" - -# Process flow - append downstream to processing -data_process = Symbol('data processing', semantic=True) -downstream = Symbol('downstream') -result = data_process >> downstream -print(result) # => "data processing downstream" -``` - -#### Practical Use Cases - -The shift operators provide a consistent way to indicate inclusion direction in high-level design: - -- **Left Shift (`<<`)**: Use when you want to prepend, prioritize, or add context before -- **Right Shift (`>>`)**: Use when you want to append, extend, or add context after - -This semantic approach allows for intuitive text manipulation and content combination while maintaining clear directional intent in your code design. - -## 7. Bitwise and Logical Operations - -Bitwise operators (`&`, `|`, `^`) work with both numeric values and logical statements, providing mathematical bitwise operations for integers and logical inference for semantic symbols. - -### Bitwise AND (`&`) - Intersection and Logical Conjunction - -```python -from symai import Symbol - -# Semantic logical conjunction - combining facts and rules -horn_rule = Symbol('The horn only sounds on Sundays.', semantic=True) -observation = Symbol('I hear the horn.') -conclusion = horn_rule & observation # => Logical inference - -# Combining evidence -evidence1 = Symbol('The suspect was seen at the scene.', semantic=True) -evidence2 = Symbol('His fingerprints were found.') -combined_evidence = evidence1 & evidence2 # => Combined evidence -``` - -### Bitwise OR (`|`) - Union and Logical Disjunction - -```python -from symai import Symbol - -# Semantic logical disjunction - alternative possibilities -option1 = Symbol('It might rain today.', semantic=True) -option2 = Symbol('It could be sunny.') -possibilities = option1 | option2 # => Multiple possibilities - -# Alternative scenarios -scenario1 = Symbol('The meeting could be postponed.', semantic=True) -scenario2 = Symbol('The meeting might be canceled.') -alternatives = scenario1 | scenario2 # => Alternative outcomes -``` - -### Bitwise XOR (`^`) - Exclusive OR - -```python -from symai import Symbol - -# Semantic exclusive choice - either/or scenarios -exclusive1 = Symbol('Either it will rain today.', semantic=True) -exclusive2 = Symbol('Or it will be sunny.') -either_or = exclusive1 ^ exclusive2 # => Exclusive alternative - -# Contradictory statements -statement1 = Symbol('The door is open.', semantic=True) -statement2 = Symbol('The door is closed.') -contradiction = statement1 ^ statement2 # => Mutually exclusive states -``` - -## 8. Arithmetic Operations - -Basic arithmetic operations (`+`, `-`) provide both syntactic combination and semantic mathematical interpretation. - -### Addition (`+`) and Subtraction (`-`) - -```python -from symai import Symbol - -enemy_text = Symbol('Hello my enemy', semantic=True) -result = enemy_text - 'enemy' + 'friend' -print(result) # => "Hello my friend" -``` - -### String Manipulation (`@`, `/`) - -The following are syntactic sugar for string concatenation and splitting: - -```python -from symai import Symbol - -string = Symbol('Hello my ') @ 'friend' # Concatenation -split_string = string / ' ' # ['Hello', 'my', 'friend'] -``` -## 9. Indexing and Slicing Operations - -The indexing and slicing operations (`__getitem__`, `__setitem__`, `__delitem__`) provide both syntactic data access and semantic key matching for dictionaries and lists. - -### Getting Items (`symbol[key]`) -```python -from symai import Symbol - -# Semantic dictionary access - finds conceptually related keys -sym_person = Symbol({'name': 'Alice', 'age': 30, 'city': 'NYC'}, semantic=True) -name_result = sym_person['Return any names'] # => 'Alice' -identity_result = sym_person['identity'] # => 'Alice' (matches 'name') -profession_result = sym_person['profession'] # => might return 'age' or relevant info - -# Semantic list access - finds conceptually matching items -sym_animals = Symbol(['cat', 'dog', 'bird', 'fish'], semantic=True) -pet_result = sym_animals['domestic animal'] - -# Color matching example -sym_colors = Symbol({'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}, semantic=True) -primary_color = sym_colors['primary color'] # => one of the hex values -``` - -### Setting Items (`symbol[key] = value`) -```python -from symai import Symbol - -# Semantic dictionary modification - maps to conceptually similar keys -sym_weather = Symbol({'temperature': 20, 'humidity': 60, 'pressure': 1013}, semantic=True) -sym_weather['Change the temperature'] = 25 # => maps to 'temperature' key -``` - -### Deleting Items (`del symbol[key]`) -```python -from symai import Symbol - -# Semantic dictionary deletion - removes conceptually matching keys -sym_person = Symbol({'first_name': 'John', 'last_name': 'Doe', 'age': 30}, semantic=True) -del sym_person['surname'] # => removes 'last_name' (conceptually equivalent) -# => {'first_name': 'John', 'age': 30} -``` - -## 10. Type Checking Operations - -### Semantic Type Validation (`isinstanceof`) - -The `isinstanceof()` method provides **semantic type checking** that goes beyond traditional Python type checking to understand conceptual types: - -```python -from symai import Symbol - -# Basic semantic type checking -number_sym = Symbol(42) -print(number_sym.isinstanceof('number')) # => True -print(number_sym.isinstanceof('string')) # => False - -# Collection type checking -list_sym = Symbol(['apple', 'banana', 'cherry']) -print(list_sym.isinstanceof('list')) # => True - -# Boolean/logical type checking -bool_sym = Symbol(True) -print(bool_sym.isinstanceof('logical value')) # => True - -# Complex semantic type recognition -person_data = Symbol({'name': 'John', 'age': 30}) -print(person_data.isinstanceof('person data')) # => True - -# More natural language type queries -user_info = Symbol({'name': 'Alice', 'age': 25, 'city': 'Wonderland'}) -print(user_info.isinstanceof('person')) # => True (understands structure represents a person) -``` - -## 11. Basic Symbolic Manipulations - -The `interpret()` method provides a way to interpret and process symbolic expressions. Each step is atomic, meaning you can build complex interpretations by chaining them together. - -```python -from symai import Symbol - -# Symbolic reasoning and analogies -analogy = Symbol('gravity : Earth :: radiation : ?') -result = analogy.interpret() -print(result) # => Sun (or similar celestial body) - -# Mathematical expression interpretation -math_expr = Symbol("∫(3x² + 2x - 5)dx") -solution = math_expr.interpret() -print(solution) # => x³ + x² - 5x + C -``` - -### Conditional Logic Processing - -```python -# Conditional interpretation with different inputs -conditional = Symbol("If x < 0 then 'negative' else if x == 0 then 'zero' else 'positive'") - -# Test with different values -print(conditional.interpret("x = -5")) # => negative -print(conditional.interpret("x = 0")) # => zero -print(conditional.interpret("x = 10")) # => positive -``` - -### System Solving and Constraints - -```python -# Mathematical system solving -system = Symbol("Find values for x and y where: x + y = 10, x - y = 4") -solution = system.interpret() -print(solution) # => x = 7, y = 3 - -# Logical reasoning with philosophical questions -reasoning = Symbol('If every event has a cause, and the universe began with an event, what philosophical question arises?') -philosophical_insight = reasoning.interpret() -print(philosophical_insight) # => What caused the first cause? (First Cause Argument) -``` - -The `interpret()` method supports can accumulate steps into one symbol: - -```python -sym_accumulate = Symbol('Relativistic electron formula') -result1 = sym_accumulate.interpret(accumulate=True) -result2 = result1.interpret('Assume the momentum to be extremely large', accumulate=True) -result3 = result2.interpret('Expand the formula to account for both mass and momentum', accumulate=True) # Ideally, we should get back to the original formula -all_results = sym_accumulate.get_results() # get all accumulated results (3) -sym_accumulate.clear_results() -``` - -## 12. Data Processing and Manipulation Operations - -### Text Cleaning and Normalization (`clean`) - -The `clean()` method normalizes whitespace, removes extra spaces, and standardizes text formatting: - -```python -sym_dirty = Symbol("This text has multiple spaces and\n\nextra newlines.\t\tAnd tabs.") -cleaned = sym_dirty.clean() -# => "This text has multiple spaces and extra newlines. And tabs." -``` - -### Content Summarization (`summarize`) - -The `summarize()` method creates concise summaries of longer content, with optional context for focused summarization: - -```python -sym_long = Symbol("Python is a high-level, interpreted programming language...") -summarized = sym_long.summarize() -# Creates a shorter version maintaining key information - -# With context for focused summarization -context_summarized = sym_long.summarize(context="Focus on Python's use in data science") -# Emphasizes data science aspects in the summary -``` - -### Content Outlining (`outline`) - -The `outline()` method extracts structure and key points from hierarchical content: - -```python -sym_complex = Symbol(""" -#Introduction to Machine Learning -Machine learning is a subset of artificial intelligence... -## Supervised Learning -### Classification -### Regression -## Unsupervised Learning -""") -outlined = sym_complex.outline() -# => ['- Machine Learning: subset of AI...', '- Supervised Learning: training...', ...] -``` - -### Content Filtering (`filter`) - -The `filter()` method selectively includes or excludes content based on criteria: - -```python -sym_mixed = Symbol("Dogs are loyal pets. Cats are independent pets. Hamsters are small pets.") - -# Exclude content matching criteria (default behavior) -filtered_ex = sym_mixed.filter(criteria="Cats") -# => "Dogs are loyal pets. Hamsters are small pets." - -# Include only content matching criteria -filtered_in = sym_mixed.filter(criteria="Dogs", include=True) -# => "Dogs are loyal pets." -``` - -### Content Modification (`modify`) - -The `modify()` method applies specified changes to content: - -```python -sym_original = Symbol("The quick brown fox jumps over the lazy dog.") -changes = "Change 'quick' to 'fast' and 'lazy' to 'sleeping'" -modified = sym_original.modify(changes=changes) -# => "The fast brown fox jumps over the sleeping dog." -``` - -### Text Replacement (`replace`) - -The `replace()` method substitutes specific text with new content: - -```python -sym_replace = Symbol("Python is a programming language. Python is easy to learn.") -replaced = sym_replace.replace("Python", "JavaScript") -# => "JavaScript is a programming language. JavaScript is easy to learn." -``` - -### Content Removal (`remove`) - -The `remove()` method eliminates specified content: - -```python -sym_extra = Symbol("This text contains [unnecessary information] that should be removed.") -removed = sym_extra.remove("[unnecessary information] ") -# => "This text contains that should be removed." -``` - -### Content Addition (`include`, `combine`) - -Both methods add content, with subtle differences in behavior: - -```python -sym_base = Symbol("This is the main content.") - -# Include additional information -included = sym_base.include("This is additional information.") -# => "This is the main content. This is additional information." - -# Combine with other content -combined = sym_base.combine("Second part of the content.") -# => "This is the main content. Second part of the content." -``` - -## 13. Pattern Matching and Intelligence Operations - -### Content Ranking (`rank`) - -The `rank()` method orders content based on specified measures and criteria: - -```python -sym_numbers = Symbol(""" -5. Learn Python basics -1. Install Python -3. Practice coding -2. Set up IDE -4. Join community -""") -ranked = sym_numbers.rank(measure='difficulty', order='desc') -# => Reorders by difficulty (descending) - -# Ranking by priority -sym_tasks = Symbol(""" -Important task: Complete project proposal -Urgent task: Fix critical bug -Optional task: Update documentation -Critical task: Deploy hotfix -""") -ranked_priority = sym_tasks.rank(measure='priority', order='asc') -``` - -### Pattern Extraction (`extract`) - -The `extract()` method identifies and extracts specific patterns or information types: - -```python -# Extract specific patterns like dates -sym_text = Symbol(""" -Project deadline: 2024-03-15 -Budget allocated: $50,000 -Team size: 8 people -Status: In Progress -""") -extracted_dates = sym_text.extract("dates and deadlines") -# => "2024-03-15" -``` - -### Code Correction (`correct`) - -The `correct()` method automatically fixes code errors based on exceptions: - -```python -# Fix syntax errors -sym_code = Symbol(""" -def calculate_sum(a b): - return a + b -""") -corrected = sym_code.correct("Fix the code", exception=SyntaxError) -# => "def calculate_sum(a, b):\n return a + b" - -# Fix type errors -sym_type_error = Symbol(""" -def process_data(items): - return items.sort() -result = process_data([3, 1, 2]) -print(result + 1) # TypeError: NoneType + int -""") -corrected_type = sym_type_error.correct("Fix the code", exception=TypeError) -# => Uses sorted() instead of sort() to return the sorted list -``` - -### Language Translation (`translate`) - -The `translate()` method converts content between languages: - -```python -sym_english = Symbol("Hello, how are you today?") -translated = sym_english.translate("Spanish") -# => "Hola, ¿cómo estás hoy?" -``` - -### Multi-Choice Classification (`choice`) - -The `choice()` method classifies content into predefined categories: - -```python -sym_weather = Symbol("Temperature: 85°F, Humidity: 70%, Conditions: Sunny") -cases = ["hot and humid", "mild", "cold and dry"] -weather_choice = sym_weather.choice(cases=cases, default="mild") -# => "hot and humid" - -# Sentiment analysis -sym_sentiment = Symbol("This product exceeded all my expectations! Absolutely wonderful!") -sentiment_cases = ["positive", "neutral", "negative"] -sentiment_choice = sym_sentiment.choice(cases=sentiment_cases, default="neutral") -# => "positive" -``` - -## 12. Data Processing and Manipulation Operations - -### Text Cleaning and Normalization (`clean`) - -The `clean()` method normalizes whitespace, removes extra spaces, and standardizes text formatting: - -```python -sym_dirty = Symbol("This text has multiple spaces and\n\nextra newlines.\t\tAnd tabs.") -cleaned = sym_dirty.clean() -# => "This text has multiple spaces and extra newlines. And tabs." -``` - -### Content Summarization (`summarize`) - -The `summarize()` method creates concise summaries of longer content, with optional context for focused summarization: - -```python -sym_long = Symbol("Python is a high-level, interpreted programming language...") -summarized = sym_long.summarize() -# Creates a shorter version maintaining key information - -# With context for focused summarization -context_summarized = sym_long.summarize(context="Focus on Python's use in data science") -# Emphasizes data science aspects in the summary -``` - -### Content Outlining (`outline`) - -The `outline()` method extracts structure and key points from hierarchical content: - -```python -sym_complex = Symbol(""" -#Introduction to Machine Learning -Machine learning is a subset of artificial intelligence... -## Supervised Learning -### Classification -### Regression -## Unsupervised Learning -""") -outlined = sym_complex.outline() -# => ['- Machine Learning: subset of AI...', '- Supervised Learning: training...', ...] -``` - -### Content Filtering (`filter`) - -The `filter()` method selectively includes or excludes content based on criteria: - -```python -sym_mixed = Symbol("Dogs are loyal pets. Cats are independent pets. Hamsters are small pets.") - -# Exclude content matching criteria (default behavior) -filtered_ex = sym_mixed.filter(criteria="Cats") -# => "Dogs are loyal pets. Hamsters are small pets." - -# Include only content matching criteria -filtered_in = sym_mixed.filter(criteria="Dogs", include=True) -# => "Dogs are loyal pets." -``` - -### Content Modification (`modify`) - -The `modify()` method applies specified changes to content: - -```python -sym_original = Symbol("The quick brown fox jumps over the lazy dog.") -changes = "Change 'quick' to 'fast' and 'lazy' to 'sleeping'" -modified = sym_original.modify(changes=changes) -# => "The fast brown fox jumps over the sleeping dog." -``` - -### Text Replacement (`replace`) - -The `replace()` method substitutes specific text with new content: - -```python -sym_replace = Symbol("Python is a programming language. Python is easy to learn.") -replaced = sym_replace.replace("Python", "JavaScript") -# => "JavaScript is a programming language. JavaScript is easy to learn." -``` - -### Content Removal (`remove`) - -The `remove()` method eliminates specified content: - -```python -sym_extra = Symbol("This text contains [unnecessary information] that should be removed.") -removed = sym_extra.remove("[unnecessary information] ") -# => "This text contains that should be removed." -``` - -### Content Addition (`include`, `combine`) - -Both methods add content, with subtle differences in behavior: - -```python -sym_base = Symbol("This is the main content.") - -# Include additional information -included = sym_base.include("This is additional information.") -# => "This is the main content. This is additional information." - -# Combine with other content -combined = sym_base.combine("Second part of the content.") -# => "This is the main content. Second part of the content." -``` - -### Semantic Mapping (`map`) - -The `map` operation applies semantic transformations to each element in an iterable based on natural language instructions. It preserves the container type and leaves non-matching elements unchanged. - -```python -# Transform characters in strings -text = Symbol("hello world") -result = text.map('convert vowels to numbers: a=1, e=2, i=3, o=4, u=5') -# => "h2ll4 w4rld" - -# Transform case selectively -caps_text = Symbol("PROGRAMMING") -result = caps_text.map('make consonants lowercase, keep vowels uppercase') -# => "prOgrAmmIng" - -# Transform fruits to vegetables, leave animals unchanged -mixed_list = Symbol(['apple', 'banana', 'cherry', 'cat', 'dog']) -result = mixed_list.map('convert all fruits to vegetables') -# => ['carrot', 'broccoli', 'spinach', 'cat', 'dog'] - -# Work with dictionaries - transforms values, preserves keys -fruit_dict = Symbol({'item1': 'apple', 'item2': 'banana', 'item3': 'cat'}) -result = fruit_dict.map('convert fruits to vegetables') -# => {'item1': 'carrot', 'item2': 'broccoli', 'item3': 'cat'} - -# Preserve container types -emotions_tuple = Symbol(('happy', 'sad', 'angry')) -weather = emotions_tuple.map('convert emotions to weather') -# => ('sunny', 'rainy', 'stormy') -``` - -**Supported Types:** -- Strings: `"abc"` → `"xyz"` (character-by-character transformation) -- Lists: `[...]` → `[...]` -- Tuples: `(...)` → `(...)` -- Sets: `{...}` → `{...}` -- Dictionaries: `{key: value}` → `{key: transformed_value}` - -**Note:** For strings, transformations apply to individual characters and the result is joined back into a string. For dictionaries, transformations apply to values while preserving keys. -### Pattern Extraction (`extract`) - -The `extract()` method identifies and extracts specific patterns or information types: - -```python -sym_contact = Symbol(""" -Contact Information: -Email: john.doe@email.com -Phone: +1-555-0123 -Address: 123 Main St, City -""") -extracted = sym_contact.extract("contact details") -# => "Email: john.doe@email.com | Phone: +1-555-0123 | Address: 123 Main St, City" - -# Extract specific patterns like dates -sym_text = Symbol(""" -Project deadline: 2024-03-15 -Budget allocated: $50,000 -Team size: 8 people -Status: In Progress -""") -extracted_dates = sym_text.extract("dates and deadlines") -# => "2024-03-15" -``` - -### Code Correction (`correct`) - -The `correct()` method automatically fixes code errors based on exceptions: - -```python -# Fix syntax errors -sym_code = Symbol(""" -def calculate_sum(a b): - return a + b -""") -corrected = sym_code.correct("Fix the code", exception=SyntaxError) -# => "def calculate_sum(a, b):\n return a + b" - -# Fix type errors -sym_type_error = Symbol(""" -def process_data(items): - return items.sort() -result = process_data([3, 1, 2]) -print(result + 1) # TypeError: NoneType + int -""") -corrected_type = sym_type_error.correct("Fix the code", exception=TypeError) -# => Uses sorted() instead of sort() to return the sorted list -``` - -### Language Translation (`translate`) - -The `translate()` method converts content between languages with optional formality control: - -```python -sym_english = Symbol("Hello, how are you today?") -translated = sym_english.translate("Spanish") -# => "Hola, ¿cómo estás hoy?" - -# Formal translation -sym_informal = Symbol("Hey there! What's up?") -translated_formal = sym_informal.translate("French", formal=True) -# => "Salut ! Quoi de neuf ?" (Note: maintains appropriate formality) -``` - -### Multi-Choice Classification (`choice`) - -The `choice()` method classifies content into predefined categories: - -```python -sym_weather = Symbol("Temperature: 85°F, Humidity: 70%, Conditions: Sunny") -cases = ["hot and humid", "mild", "cold and dry"] -weather_choice = sym_weather.choice(cases=cases, default="mild") -# => "hot and humid" - -# Sentiment analysis -sym_sentiment = Symbol("This product exceeded all my expectations! Absolutely wonderful!") -sentiment_cases = ["positive", "neutral", "negative"] -sentiment_choice = sym_sentiment.choice(cases=sentiment_cases, default="neutral") -# => "positive" -``` - -### Format Conversion (`convert`) - -The `convert()` method transforms data between different formats: - -```python -sym_json = Symbol('{"name": "John", "age": 30, "city": "New York"}') - -yaml_converted = sym_json.convert("YAML") -# => "name: John\nage: 30\ncity: New York" - -xml_converted = sym_json.convert("XML") -# => "\n John\n 30\n New York\n" - -# Convert CSV to HTML table -sym_csv = Symbol("Name,Age,Department\nAlice,28,Engineering\nBob,35,Marketing") -table_converted = sym_csv.convert("HTML table") -# => Complete HTML table with thead and tbody -``` - -### Content Transcription (`transcribe`) - -The `transcribe()` method modifies content style, tone, and formality: - -```python -sym_informal = Symbol("Hey there! How's it going? Hope you're doing well!") -formal_transcribed = sym_informal.transcribe("make it formal and professional") -# => "I hope this message finds you well." - -sym_technical = Symbol("The system crashed because of insufficient memory allocation.") -simple_transcribed = sym_technical.transcribe("explain in simple terms for non-technical audience") -# => "The system stopped working because it didn't have enough digital space to run properly." -``` - -## 15. Execution Control and Code Operations - -### Code Analysis (`analyze`) - -The `analyze()` method provides insights into code issues and exceptions: - -```python -sym_code = Symbol("print('Hello World')") -try: - raise ValueError("Sample error for testing") -except Exception as e: - analyzed = sym_code.analyze(exception=e, query="What went wrong?") -# => Detailed analysis of the error context -``` - -### Code Execution (`execute`, `fexecute`) - -Execute Python code and return comprehensive results: - -```python -sym_code = Symbol(""" -def run(): - return 2 + 3 -res = run() -""") -executed = sym_code.execute() -# => {'globals': {...}, 'locals': {...}, 'locals_res': 5} - -# Fallback execution -fexecuted = sym_code.fexecute() -# => Similar execution with fault tolerance -``` - -### Code Simulation (`simulate`) - -The `simulate()` method provides step-by-step execution traces: - -```python -sym_algorithm = Symbol("x = 5; y = 10; result = x + y") -simulated = sym_algorithm.simulate() -# => "Step 4: Set result = 15" - -# Complex algorithm simulation -sym_fibonacci = Symbol("def fibonacci(n): return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)") -algorithm_sim = sym_fibonacci.simulate() -# => Detailed pseudocode execution trace -``` - -### Information Sufficiency (`sufficient`) - -Check if provided information is adequate for specific purposes: - -```python -sym_info = Symbol("Product Name: UltraBook Pro\nPrice: $1299\nRAM: 16GB") -sufficient_check = sym_info.sufficient("Is this enough information to make a purchase decision?") -# => False (missing key details) -``` - -### List Processing (`list`, `foreach`) - -Extract and process lists based on criteria: - -```python -sym_employees = Symbol(""" -Bob - Manager - $85000 -Carol - Designer - $65000 -David - Engineer - $72000 -""") - -engineers_list = sym_employees.list("employees who are engineers") -# => ['David'] - -# Apply operations to each item -sym_numbers = Symbol([1, 2, 3, 4, 5]) -squared_numbers = sym_numbers.foreach("each number", "square the number") -# => ['1', '4', '9', '16', '25'] -``` - -### Fault-Tolerant Execution (`ftry`) - -Execute operations with retry logic and error handling: - -```python -sym_test = Symbol("test data") -# Automatically retries failed operations -ftry_result = sym_test.ftry(expression, retries=2) -# => Successful execution after potential retries -``` - -## 16. Dictionary Handling Operations - -### Dictionary Creation (`dict`) - -Convert various data types into structured dictionaries: - -```python -sym_text = Symbol("I have apples, oranges, and bananas in my kitchen.") -dict_result = sym_text.dict("categorize fruits") -# => {'fruits': ['apples', 'oranges', 'bananas'], 'description': ['I have', 'in my kitchen.']} - -sym_shopping = Symbol("milk, bread, eggs, apples, cheese, chicken, broccoli, rice") -food_dict = sym_shopping.dict("organize by food categories") -# => {'dairy': ['milk', 'cheese'], 'produce': ['apples', 'broccoli'], ...} -``` - -## 17. Template and Styling Operations - -### Template Substitution (`template`) - -Replace placeholders in templates with Symbol values: - -```python -sym_name = Symbol("Alice") -template_str = "Hello {{placeholder}}, welcome to our service!" -templated_result = sym_name.template(template_str) -# => "Hello Alice, welcome to our service!" - -# Custom placeholder -sym_product = Symbol("Premium Headphones") -custom_template = "Product: ***ITEM*** - Now available!" -custom_templated = sym_product.template(custom_template, placeholder="***ITEM***") -# => "Product: Premium Headphones - Now available!" -``` - -### Content Styling (`style`) - -Apply formatting and styling to content: - -```python -sym_content = Symbol("This is basic text that needs styling.") -styled_result = sym_content.style("Make this text bold and italic") -# => "***This is basic text that needs styling.***" - -sym_code = Symbol("print('Hello World')") -styled_code = sym_code.style("Format as Python code with syntax highlighting", libraries=["python"]) -# => "```python\nprint('Hello World')\n```" -``` - -## 18. Data Clustering Operations - -### Semantic Clustering (`cluster`) - -Group similar items based on semantic similarity: - -```python -sym_fruits = Symbol(["apple", "banana", "cherry", "orange", "grape"]) -clustered_result = sym_fruits.cluster(metric='cosine', min_cluster_size=2) -# => Groups semantically similar items together - -sym_sentences = Symbol([ - "The weather is sunny today.", - "It's raining heavily outside.", - "Beautiful sunny weather today." -]) -sentence_clusters = sym_sentences.cluster(min_cluster_size=2) -# => Groups similar sentiment/topic sentences -``` - -Under the hood, the `cluster` method uses `sklearn`'s HDBSCAN [algorithm](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.HDBSCAN.html#sklearn.cluster.HDBSCAN). You can pass as `kwargs` any parameter that is accepted by the `HDBSCAN` class, such as `min_samples`, `min_cluster_size`, `metric`, etc. - -## 19. Embedding and Similarity Operations - -### Embedding Generation (`embed`, `embedding`) - -Create vector embeddings for semantic operations: - -```python -sym_text = Symbol("hello world") -embedded_result = sym_text.embed() -# => Embedding vectors with shape information - -# Access embedding property -embedding_value = sym_text.embedding -# => NumPy array of embeddings -``` - -### Similarity and Distance Calculations - -Calculate semantic similarity and distance between symbols: - -```python -sym1 = Symbol("hello world") -sym2 = Symbol("hi there") - -similarity_result = sym1.similarity(sym2, metric='cosine') -distance_result = sym1.distance(sym2, kernel='gaussian') -``` - -### Embedding Packaging (`zip`) - -Format embeddings for storage and retrieval: - -```python -sym_text = Symbol("hello world") -zip_result = sym_text.zip() -# => [(id, embedding_list, query_dict), ...] -``` - -## 20. Input/Output Handling Operations - -### File Operations (`open`) - -Read file contents into Symbol values: - -```python -# Open file with path parameter -sym_empty = Symbol() -opened_result = sym_empty.open("/path/to/file.txt") -# => Symbol containing file contents - -# Open file with path as Symbol value -sym_path = Symbol("/path/to/file.txt") -opened_from_value = sym_path.open() -# => Symbol containing file contents -``` - -### User Input (`input`) - -Handle interactive user input (requires user interaction): - -```python -sym = Symbol() -user_input = sym.input() # Prompts for user input -``` - -## 21. Persistence Operations - -### Saving Symbols (`save`) - -Persist Symbol data to files with various options: - -```python -sym_test = Symbol("Hello, persistence test!") - -# Save as pickle (serialized) -sym_test.save("/path/to/file.pkl", serialize=True) - -# Save as text -sym_test.save("/path/to/file.txt", serialize=False) - -# Control file replacement -sym_test.save("/path/to/file.txt", replace=False) # Creates new file with suffix -sym_test.save("/path/to/file.txt", replace=True) # Overwrites existing file -``` - -### Loading Symbols (`load`) - -Load previously saved Symbol data: - -```python -loader_sym = Symbol() -loaded_sym = loader_sym.load("/path/to/file.pkl") -# => Restored Symbol with original data -``` - -### Dynamic Function Expansion (`expand`) - -Generate and attach new functions based on descriptions: - -```python -sym_task = Symbol("Calculate the fibonacci sequence up to 10 numbers") -func_name = sym_task.expand() -# => Generated function name, function attached as Symbol attribute -``` - -## 22. Output Processing Operations - -### Output Handling (`output`) - -Process and format Symbol output with custom handlers: - -```python -sym_test = Symbol("Hello, output test!") - -# Basic output processing -result = sym_test.output() -# => Structured output with processed information - -# Custom handler function -def custom_handler(input_dict): - # Process the input dictionary - pass - -result_with_handler = sym_test.output(handler=custom_handler) -# => Output processed through custom handler - -# With additional arguments -result_with_args = sym_test.output("arg1", "arg2", custom_param="value") -# => Output including method arguments and parameters -``` diff --git a/symbolicai-main/symbolicai-main/docs/source/INSTALLATION.md b/symbolicai-main/symbolicai-main/docs/source/INSTALLATION.md deleted file mode 100644 index a3bfb6080ed280dcea9467e9133d2a4cccc5f853..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/INSTALLATION.md +++ /dev/null @@ -1,187 +0,0 @@ -# Installation - -## Core Features - -To get started with SymbolicAI, you can install it using pip: - -```bash -pip install symbolicai -``` - -### Setting up a neurosymbolic API Key - -Before using SymbolicAI, you need to set up API keys for the various engines. Currently, SymbolicAI supports the following neurosymbolic engines through API: OpenAI, Anthropic. We also support {doc}`local neurosymbolic engines `, such as llama.cpp and huggingface. - -```bash -# Linux / MacOS -export NEUROSYMBOLIC_ENGINE_API_KEY="…" -export NEUROSYMBOLIC_ENGINE_MODEL="…" -``` - -```bash -# Windows (PowerShell) -$Env:NEUROSYMBOLIC_ENGINE_API_KEY="…" -$Env:NEUROSYMBOLIC_ENGINE_MODEL="…" -``` - -```bash -# Jupyter Notebooks -%env NEUROSYMBOLIC_ENGINE_API_KEY=… -%env NEUROSYMBOLIC_ENGINE_MODEL=… -``` - -### Optional Features - -SymbolicAI uses multiple engines to process text, speech and images. We also include search engine access to retrieve information from the web. To use all of them, you will need to also install the following dependencies and assign the API keys to the respective engines. - -```bash -pip install "symbolicai[wolframalpha]" -pip install "symbolicai[whisper]" -pip install "symbolicai[selenium]" -pip install "symbolicai[serpapi]" -pip install "symbolicai[pinecone]" -``` - -Or, install all optional dependencies at once: - -```bash -pip install "symbolicai[all]" -``` - -And export the API keys, for example: - -```bash -# Linux / MacOS -export SYMBOLIC_ENGINE_API_KEY="" -export SEARCH_ENGINE_API_KEY="" -export OCR_ENGINE_API_KEY="" -export INDEXING_ENGINE_API_KEY="" - -# Windows (PowerShell) -$Env:SYMBOLIC_ENGINE_API_KEY="" -$Env:SEARCH_ENGINE_API_KEY="" -$Env:OCR_ENGINE_API_KEY="" -$Env:INDEXING_ENGINE_API_KEY="" -``` - -See below for the entire list of keys that can be set via environment variables or a configuration file. - -### Additional Requirements - -**SpeechToText Engine**: Install `ffmpeg` for audio processing (based on OpenAI's [whisper](https://openai.com/blog/whisper/)) - -```bash -# Linux -sudo apt update && sudo apt install ffmpeg - -# MacOS -brew install ffmpeg - -# Windows -choco install ffmpeg -``` - -**WebCrawler Engine**: For `selenium`, we automatically install the driver with `chromedriver-autoinstaller`. Currently we only support Chrome as the default browser. - -## Configuration Management - -SymbolicAI now features a configuration management system with priority-based loading. The configuration system looks for settings in three different locations, in order of priority: - -1. **Debug Mode** (Current Working Directory) - - Highest priority - - Only applies to `symai.config.json` - - Useful for development and testing - -2. **Environment-Specific Config** (Python Environment) - - Second priority - - Located in `{python_env}/.symai/` - - Ideal for project-specific settings - -3. **Global Config** (Home Directory) - - Lowest priority - - Located in `~/.symai/` - - Default fallback for all settings - -### Configuration Files - -The system manages three main configuration files: -- `symai.config.json`: Main SymbolicAI configuration -- `symsh.config.json`: Shell configuration -- `symserver.config.json`: Server configuration - -### Viewing Your Configuration - -Before using the package, we recommend inspecting your current configuration setup using the command below. This will create all the necessary configuration files. - -```bash -symconfig -``` - -This command will show: -- All configuration locations -- Active configuration paths -- Current settings (with sensitive data truncated) - -### Configuration Priority Example - -```console -my_project/ # Debug mode (highest priority) -└── symai.config.json # Only this file is checked in debug mode - -{python_env}/.symai/ # Environment config (second priority) -├── symai.config.json -├── symsh.config.json -└── symserver.config.json - -~/.symai/ # Global config (lowest priority) -├── symai.config.json -├── symsh.config.json -└── symserver.config.json -``` - -If a configuration file exists in multiple locations, the system will use the highest-priority version. If the environment-specific configuration is missing or invalid, the system will automatically fall back to the global configuration in the home directory. - -### Best Practices - -- Use the global config (`~/.symai/`) for your default settings -- Use environment-specific configs for project-specific settings -- Use debug mode (current directory) for development and testing -- Run `symconfig` to inspect your current configuration setup - -This addition to the README clearly explains: -1. The priority-based configuration system -2. The different configuration locations and their purposes -3. How to view and manage configurations -4. Best practices for configuration management - -### Configuration File - -You can specify engine properties in a `symai.config.json` file in your project path. This will replace the environment variables. -Example of a configuration file with all engines enabled: -```json -{ - "NEUROSYMBOLIC_ENGINE_API_KEY": "", - "NEUROSYMBOLIC_ENGINE_MODEL": "gpt-4o", - "SYMBOLIC_ENGINE_API_KEY": "", - "SYMBOLIC_ENGINE": "wolframalpha", - "EMBEDDING_ENGINE_API_KEY": "", - "EMBEDDING_ENGINE_MODEL": "text-embedding-3-small", - "SEARCH_ENGINE_API_KEY": "", - "SEARCH_ENGINE_MODEL": "sonar", - "TEXT_TO_SPEECH_ENGINE_API_KEY": "", - "TEXT_TO_SPEECH_ENGINE_MODEL": "tts-1", - "INDEXING_ENGINE_API_KEY": "", - "INDEXING_ENGINE_ENVIRONMENT": "us-west1-gcp", - "DRAWING_ENGINE_API_KEY": "", - "DRAWING_ENGINE_MODEL": "dall-e-3", - "VISION_ENGINE_MODEL": "openai/clip-vit-base-patch32", - "OCR_ENGINE_API_KEY": "", - "SPEECH_TO_TEXT_ENGINE_MODEL": "turbo", - "SUPPORT_COMMUNITY": true -} -``` - -With these steps completed, you should be ready to start using SymbolicAI in your projects. - -> ❗️**NOTE**❗️Our framework allows you to support us train models for local usage by enabling the data collection feature. On application startup we show the terms of services and you can activate or disable this community feature. We do not share or sell your data to 3rd parties and only use the data for research purposes and to improve your user experience. To change this setting open the `symai.config.json` and turn it on/off by setting the `SUPPORT_COMMUNITY` property to `True/False` via the config file or the respective environment variable. -> ❗️**NOTE**❗️By default, the user warnings are enabled. To disable them, export `SYMAI_WARNINGS=0` in your environment variables. diff --git a/symbolicai-main/symbolicai-main/docs/source/INTRODUCTION.md b/symbolicai-main/symbolicai-main/docs/source/INTRODUCTION.md deleted file mode 100644 index 91746c2a190d4afe4a2d6bac90380e03adbb606c..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/INTRODUCTION.md +++ /dev/null @@ -1,75 +0,0 @@ -# Introduction - -**SymbolicAI: A Neuro-Symbolic Perspective on Large Language Models (LLMs)** - -## Overview - -SymbolicAI is a framework that leverages machine learning, specifically Large Language Models (LLMs), as its foundation and composes operations based on task-specific prompting. Our approach adopts a divide-and-conquer strategy to break down complex problems into smaller, more manageable tasks. By reassembling these operations, we can solve intricate problems efficiently. - -Read [**full paper here**](https://arxiv.org/abs/2402.00854). - -## Key Features - -- Seamless transition between differentiable and classical programming -- Neuro-symbolic computation using LLMs -- Composable operations for complex problem-solving -- Integration with various engines (OpenAI, WolframAlpha, OCR, etc.) -- Support for multimodal inputs and outputs - -## 🤷‍♂️ Why SymbolicAI? - -SymbolicAI aims to bridge the gap between classical programming (Software 1.0) and modern data-driven programming (Software 2.0). It enables the creation of software applications that harness the power of large language models while maintaining the benefits of composability and inheritance from object-oriented programming. - -By using SymbolicAI, you can traverse the spectrum between the classical programming realm and the data-driven programming realm, as illustrated in the following figure: - - - -We adopt a divide-and-conquer approach, breaking down complex problems into smaller, manageable tasks. We use the expressiveness and flexibility of LLMs to evaluate these sub-problems. By re-combining the results of these operations, we can solve the broader, more complex problem. - -In time, and with sufficient data, we can gradually transition from general-purpose LLMs with `zero` and `few-shot` learning capabilities to specialized, fine-tuned models designed to solve specific problems. This strategy enables the design of operations with fine-tuned, task-specific behavior. - -## Core Concepts - -1. **Symbols**: All data objects are treated as symbols, with natural language as the primary interface for interaction. -2. **Operations**: Contextualized functions that manipulate symbols and return new objects. -3. **Expressions**: Non-terminal symbols that can be further evaluated, allowing for complex computational graphs. -4. **Engines**: Various backends (e.g., GPT-3, WolframAlpha, CLIP) that power different types of computations and transformations. - -## More fun facts! - -SymbolicAI is fundamentally inspired by the [`neuro-symbolic programming paradigm`](https://arxiv.org/abs/2210.05050). - -**Neuro-symbolic programming** is an artificial intelligence and cognitive computing paradigm that combines the strengths of deep neural networks and symbolic reasoning. - -**Deep neural networks** are machine learning algorithms inspired by the structure and function of biological neural networks. They excel in tasks such as image recognition and natural language processing. However, they struggle with tasks that necessitate explicit reasoning, like long-term planning, problem-solving, and understanding causal relationships. - -**Symbolic reasoning** uses formal languages and logical rules to represent knowledge, enabling tasks such as planning, problem-solving, and understanding causal relationships. While symbolic reasoning systems excel in tasks requiring explicit reasoning, they fall short in tasks demanding pattern recognition or generalization, like image recognition or natural language processing. - -**Neuro-symbolic programming** aims to merge the strengths of both neural networks and symbolic reasoning, creating AI systems capable of handling various tasks. This combination is achieved by using neural networks to extract information from data and utilizing symbolic reasoning to make inferences and decisions based on that data. Another approach is for symbolic reasoning to guide the neural networks' generative process and increase interpretability. - -**Embedded accelerators for LLMs** will likely be ubiquitous in future computation platforms, including wearables, smartphones, tablets, and notebooks. These devices will incorporate models similar to GPT-3, ChatGPT, OPT, or Bloom. - - - -LLMs are expected to perform a wide range of computations, like natural language understanding and decision-making. Additionally, neuro-symbolic computation engines will learn how to tackle unseen tasks and resolve complex problems by querying various data sources for solutions and executing logical statements on top. -To ensure the content generated aligns with our objectives, it is crucial to develop methods for instructing, steering, and controlling the generative processes of machine learning models. As a result, our approach works to enable active and transparent flow control of these generative processes. - - - -The figure above depicts this generative process as shifting the probability mass of an input stream toward an output stream in a contextualized manner. With properly designed conditions and expressions, you can validate and guide the behavior towards a desired outcome or repeat expressions that fail to meet requirements. Our approach consists of defining a set of _fuzzy_ operations to manipulate the data stream and condition LLMs to align with our goals. We regard all data objects – such as strings, letters, integers, and arrays – as symbols and view natural language as the primary interface for interaction. See the following figure: - - - -As long as our goals can be expressed through natural language, LLMs can be used for neuro-symbolic computations. -Consequently, we develop operations that manipulate these symbols to construct new symbols. Each symbol can be interpreted as a statement, and multiple statements can be combined to formulate a logical expression. - -By combining statements together, we can build causal relationship functions and complete computations, transcending reliance purely on inductive approaches. The resulting computational stack resembles a neuro-symbolic computation engine at its core, facilitating the creation of new applications in tandem with established frameworks. - -## Future Directions - -- Meta-learning semantic concepts on top of neuro-symbolic expressions -- Self-evolving and self-healing API -- Integration with reinforcement learning -- Advancement in prompt design and value alignment methods - -SymbolicAI opens up new possibilities for creating applications that can perform self-analysis and self-repair, pushing the boundaries of what's possible with LLMs and neuro-symbolic computation. \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/docs/source/LICENSE b/symbolicai-main/symbolicai-main/docs/source/LICENSE deleted file mode 100644 index 6d3f4b756de16265dadb746bebd023a4a92eaeec..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/LICENSE +++ /dev/null @@ -1,32 +0,0 @@ -License -======= - -BSD 3-Clause License - -Copyright (c) 2024, ExtensityAI FlexCo. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/symbolicai-main/symbolicai-main/docs/source/QUICKSTART.md b/symbolicai-main/symbolicai-main/docs/source/QUICKSTART.md deleted file mode 100644 index a635791fd9a35dc27703a7f4a384bc35d314ecf7..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/QUICKSTART.md +++ /dev/null @@ -1,92 +0,0 @@ -# Quick Start Guide - -This guide will help you get started with SymbolicAI, demonstrating basic usage and key features. - -**Note**: the most accurate documentation is the _code_, so be sure to check out the tests. Look for the `mandatory` mark since those are the features that were tested and are guaranteed to work. - -For more detailed information about usage, refer to the materials available [here](https://extensityai.gitbook.io/symbolicai/features/contracts) and [here](https://extensityai.gitbook.io/symbolicai/features/primitives). - -To start, import the library by using: - -```python -from symai import Symbol -``` - -## Creating and Manipulating Symbols - -Our `Symbolic API` is based on object-oriented and compositional design patterns. The `Symbol` class serves as the base class for all functional operations, and in the context of symbolic programming (fully resolved expressions), we refer to it as a terminal symbol. The Symbol class contains helpful operations that can be interpreted as expressions to manipulate its content and evaluate new Symbols ``. - -```python -# Create a Symbol -S = Symbol("Welcome to our tutorial.") -# Translate the Symbol -print(S.translate('German')) # Output: Willkommen zu unserem Tutorial. -``` - -### Ranking Objects - -Our API can also execute basic data-agnostic operations like `filter`, `rank`, or `extract` patterns. For instance, we can rank a list of numbers: - -```python -# Ranking objects -import numpy as np - -S = Symbol(np.array([1, 2, 3, 4, 5, 6, 7])) -print(S.rank(measure='numerical', order='descending')) # Output: ['7', '6', '5', '4', '3', '2', '1'] -``` - -### Evaluating Expressions - -Evaluations are resolved in the language domain and by best effort. We showcase this on the example of [word2vec](https://arxiv.org/abs/1301.3781). - -**Word2Vec** generates dense vector representations of words by training a shallow neural network to predict a word based on its neighbors in a text corpus. These resulting vectors are then employed in numerous natural language processing applications, such as sentiment analysis, text classification, and clustering. - -In the example below, we can observe how operations on word embeddings (colored boxes) are performed. Words are tokenized and mapped to a vector space where semantic operations can be executed using vector arithmetic. - - - -Similar to word2vec, we aim to perform contextualized operations on different symbols. However, as opposed to operating in vector space, we work in the natural language domain. This provides us the ability to perform arithmetic on words, sentences, paragraphs, etc., and verify the results in a human-readable format. - -The following examples display how to evaluate such an expression using a string representation: - -```python -# Word analogy -S = Symbol('King - Man + Women').interpret() -print(S) # Output: Queen -``` - -### Dynamic Casting - -We can also subtract sentences from one another, where our operations condition the neural computation engine to evaluate the Symbols by their best effort. In the subsequent example, it identifies that the word `enemy` is present in the sentence, so it deletes it and replaces it with the word `friend` (which is added): - -```python -# Sentence manipulation -S = Symbol('Hello my enemy').sem - 'enemy' + 'friend' -print(S) # Output: Hello my friend -``` - -Additionally, the API performs dynamic casting when data types are combined with a Symbol object. If an overloaded operation of the Symbol class is employed, the Symbol class can automatically cast the second object to a Symbol. This is a convenient way to perform operations between `Symbol` objects and other data types, such as strings, integers, floats, lists, etc., without cluttering the syntax. - -### Probabilistic Programming - -In this example, we perform a fuzzy comparison between two numerical objects. The `Symbol` variant is an approximation of `numpy.pi`. Despite the approximation, the fuzzy equals `==` operation still successfully compares the two values and returns `True`. - -```python -# Fuzzy comparison -# # Fuzzy comparison -S = Symbol('3.14159...', semantic=True) -print(S == 'π') # Output: True -``` - -### 🧠 Causal Reasoning - -The main goal of our framework is to enable reasoning capabilities on top of the statistical inference of Language Models (LMs). As a result, our `Symbol` objects offers operations to perform deductive reasoning expressions. One such operation involves defining rules that describe the causal relationship between symbols. The following example demonstrates how the `&` operator is overloaded to compute the logical implication of two symbols. - -```python -S1 = Symbol('The horn only sounds on Sundays.', semantic=True) -S2 = Symbol('I hear the horn.') -res = S1 & S2 # Therefore, it is Sunday. -``` - -### 🪜 Next Steps -Now, there are tools like DeepWiki that provide better documentation than we could ever write, and we don’t want to compete with that; we'll correct it where it's plain wrong. Please go read SymbolicAI's DeepWiki [page](https://deepwiki.com/ExtensityAI/symbolicai/). There's a lot of interesting stuff in there. Last but not least, check out our [paper](https://arxiv.org/abs/2402.00854) that describes the framework in detail. If you like watching videos, we have a series of tutorials that you can find [here](https://extensityai.gitbook.io/symbolicai/tutorials/video_tutorials). diff --git a/symbolicai-main/symbolicai-main/docs/source/SUMMARY.md b/symbolicai-main/symbolicai-main/docs/source/SUMMARY.md deleted file mode 100644 index 7adc8e9c3f8f1b2e20d380ca4cf0086dab40051c..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/SUMMARY.md +++ /dev/null @@ -1,41 +0,0 @@ -# Summary - -* [Introduction](INTRODUCTION.md) -* [Installation](INSTALLATION.md) -* [Quick Start Guide](QUICKSTART.md) - -## Engines -* [Neuro-Symbolic Engine](ENGINES/neurosymbolic_engine.md) -* [CLIP Engine](ENGINES/clip_engine.md) -* [Custom Engine](ENGINES/custom_engine.md) -* [Drawing Engine](ENGINES/drawing_engine.md) -* [File Engine](ENGINES/file_engine.md) -* [Indexing Engine](ENGINES/indexing_engine.md) -* [Local Engine](ENGINES/local_engine.md) -* [OCR Engine](ENGINES/ocr_engine.md) -* [Search Engine](ENGINES/search_engine.md) -* [Speech Engine](ENGINES/speech_engine.md) -* [Symbolic Engine](ENGINES/symbolic_engine.md) -* [Webcrawler Engine](ENGINES/webcrawler_engine.md) - -## Features -* [Contracts](FEATURES/contracts.md) -* [Primitives](FEATURES/primitives.md) -* [Operations](FEATURES/operations.md) -* [Expressions](FEATURES/expressions.md) -* [Error Handling](FEATURES/error_handling.md) -* [Module Import](FEATURES/import.md) - -## Tutorials -* [Chatbot Tutorial](TUTORIALS/chatbot.md) -* [Handling Large Contexts](TUTORIALS/context.md) -* [SQL Data Query](TUTORIALS/data_query.md) -* [Video Tutorials](TUTORIALS/video_tutorials.md) - -## Tools -* [Chatbot CLI](TOOLS/chatbot.md) -* [Package Manager](TOOLS/packages.md) -* [Shell](TOOLS/shell.md) - -## License -* [License](LICENSE) diff --git a/symbolicai-main/symbolicai-main/docs/source/TOOLS/chatbot.md b/symbolicai-main/symbolicai-main/docs/source/TOOLS/chatbot.md deleted file mode 100644 index 1a45787704e0d809cb284640c022816cdfbbf7cb..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/TOOLS/chatbot.md +++ /dev/null @@ -1,24 +0,0 @@ -# Chatbot - ---- - -## ⚠️ Outdated or Deprecated Documentation ⚠️ -This documentation is outdated and may not reflect the current state of the SymbolicAI library. This page might be revived or deleted entirely as we continue our development. We recommend using more modern tools that infer the documentation from the code itself, such as [DeepWiki](https://deepwiki.com/ExtensityAI/symbolicai). This will ensure you have the most accurate and up-to-date information and give you a better picture of the current state of the library. - ---- - -You can engage in a basic conversation with `Symbia`, a chatbot that uses `SymbolicAI` to detect the content of your request and switch between different contextual modes to answer your questions. These modes include search engines, speech engines, and more. To start the chatbot, simply run: - -```bash -$> symchat -``` - -This will launch a chatbot interface: - -```bash -Symbia: Hi there! I'm Symbia, your virtual assistant. How may I help you? -$> -``` - -To exit the conversation, type `exit`, `quit`, or press `Ctrl+C`. -You can also load our chatbot `SymbiaChat` into a jupyter notebook and process step-wise requests. diff --git a/symbolicai-main/symbolicai-main/docs/source/TOOLS/packages.md b/symbolicai-main/symbolicai-main/docs/source/TOOLS/packages.md deleted file mode 100644 index b92b1f695c9d3ef4dadf0fc6413d8ea2c718727e..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/TOOLS/packages.md +++ /dev/null @@ -1,143 +0,0 @@ -# Packages - -## 📦 Package Manager - -We provide a package manager called `sympkg` that allows you to manage extensions from the command line. With `sympkg`, you can install, remove, list installed packages, or update a module. - -To use `sympkg`, follow the steps below: - -1. Open your terminal or PowerShell. -2. Run the following command: `sympkg []` - -The available commands are: - -- `i` or `install`: Install a new package. To install a package, use the following command: `sympkg i [--local-path PATH] [--submodules]` -- `r` or `remove`: Remove an installed package. To remove a package, use the following command: `sympkg r ` -- `l` or `list`: List all installed packages. To list installed packages, use the following command: `sympkg l` -- `u` or `update`: Update an installed package. To update a package, use the following command: `sympkg u [--submodules]` -- `U` or `update-all`: Update all installed packages. To update all packages, use the following command: `sympkg U [--submodules]` - -For more information on each command, you can use the `--help` flag. For example, to get help on the `i` command, use the following command: `sympkg i --help`. - -### Installation Options - -When installing packages, you can use the following options: - -- `--local-path PATH` or `-l PATH`: Install a package from a local directory instead of GitHub in format `/`. -- `--submodules` or `-s`: Initialize Git submodules when cloning a package from GitHub. - -Example: `sympkg i ExtensityAI/symask --submodules` or `sympkg i ExtensityAI/symask /path/to/local/package` - -### Update Options - -When updating packages, you can use the following option: - -- `--submodules` or `-s`: Update Git submodules along with the main repository. - -Example: `sympkg u ExtensityAI/symask --submodules` - -Note: The package manager is based on GitHub, so you will need `git` installed to install or update packages. The packages names use the GitHub `/` convention. - -Happy package managing! - -## 📦 Package Runner - -The Package Runner is a command-line tool that allows you to run packages via alias names. It provides a convenient way to execute commands or functions defined in packages. You can access the Package Runner by using the `symrun` command in your terminal or PowerShell. - -### Usage - -To use the Package Runner, you can run the following command: - -```bash -$> symrun [] [--submodules] | [] -``` - -The most commonly used Package Runner commands are: - -- ` []`: Run an alias -- `c `: Create a new alias -- `l`: List all aliases -- `r `: Remove an alias - -### Examples - -Here are a few examples to illustrate how to use the Package Runner: - -The following command runs the specified `my_alias` with the provided arguments `arg1`, `arg2`, `kwarg1` and `kwarg2`, where `arg1` and `arg2` are considered as *args parameter and `kwarg1` and `kwarg1` **kwargs key-value arguments. These arguments will be passed on to the executable expression within the expression. - -```bash -$> symrun my_alias arg1 arg2 kwarg1=value1 kwarg2=value2 -``` -The following command runs the alias with the `--submodules` flag, which will initialize Git submodules if the package needs to be installed: - -```bash -$> symrun my_alias arg1 arg2 --submodules -``` - -The following command creates a new alias named `my_alias` that points to `/`: - -```bash -$> symrun c my_alias / -``` - -The following command lists all the aliases that have been created: - -```bash -$> symrun l -``` - -The following command removes the alias named `my_alias`: - -```bash -$> symrun r my_alias -``` - -### Alias File - -The Package Runner stores aliases in a JSON file named `aliases.json`. This file is located in the `.symai/packages/` directory in your home directory (`~/.symai/packages/`). You can view the contents of this file to see the existing aliases. - -Here is an example how to use the `sympkg` and `symrun` via shell: -![Demo Usage of symask](https://raw.githubusercontent.com/ExtensityAI/symbolicai/main/assets/images/screen1.jpeg) - -> ❗️**NOTE**❗️If the alias specified cannot be found in the alias file, the Package Runner will attempt to run the command as a package. If the package is not found or an error occurs during execution, an appropriate error message will be displayed. - -That's it! You now have a basic understanding of how to use the Package Runner provided to run packages and aliases from the command line. - -## 📦 Package Initializer - -The Package Initializer is a command-line tool provided that allows developers to create new GitHub packages from the command line. It automates the process of setting up a new package directory structure and files. You can access the Package Initializer by using the `symdev` command in your terminal or PowerShell. - -### Usage - -To use the Package Initializer, you can run the following command: - -```bash -$> symdev c / -``` - -The most commonly used Package Initializer command is: - -- `c /`: Create a new package - -### Examples - -Here is an example to illustrate how to use the Package Initializer: - -```bash -$> symdev c symdev/my_package -``` - -This command creates a new package named `my_package` under the GitHub username `symdev`. - -The Package Initializer creates the following files and directories: - -- `.gitignore`: Specifies files and directories that should be ignored by Git. -- `LICENSE`: Contains the license information for the package. -- `README.md`: Contains the description and documentation for the package. -- `requirements.txt`: Lists the packages and dependencies required by the package. -- `package.json`: Provides metadata for the package, including version, name, description, and expressions. -- `src/func.py`: Contains the main function and expression code for the package. - -The Package Initializer creates the package in the `.symai/packages/` directory in your home directory (`~/.symai/packages//`). -Within the created package you will see the `package.json` config file defining the new package metadata and `symrun` entry point and offers the declared expression types to the `Import` class. -Read more about the {doc}`Import class <../FEATURES/import>` diff --git a/symbolicai-main/symbolicai-main/docs/source/TOOLS/shell.md b/symbolicai-main/symbolicai-main/docs/source/TOOLS/shell.md deleted file mode 100644 index b67900ba6400f9f81d19e414389fc90b7c2b12a0..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/TOOLS/shell.md +++ /dev/null @@ -1,203 +0,0 @@ -# Shell Command Tool - -The Shell Command Tool is a basic shell command support tool that translates natural language commands into shell commands. To start the Shell Command Tool, simply run: - -```bash -symsh "" -``` - -For more information about the tool and available arguments, use the `--help` flag: - -```bash -symsh --help -``` - -Here is an example of how to use the Shell Command Tool: - -```bash -$> symsh "PowerShell edit registry entry" - -# :Output: -# Set-ItemProperty -Path -Name -Value - -$> symsh "Set-ItemProperty -Path -Name -Value " --add "path='/Users/myuser' name=Demo value=SymbolicAI" - -# :Output: -# Set-ItemProperty -Path '/Users/myuser' -Name Demo -Value SymbolicAI - -$> symsh "Set-ItemProperty -Path '/Users/myuser' -Name Demo -Value SymbolicAI" --del "string quotes" - -# :Output: -# Set-ItemProperty -Path /Users/myuser -Name Demo -Value SymbolicAI - -$> symsh "Set-ItemProperty -Path '/Users/myuser' -Name Demo -Value SymbolicAI" --convert "linux" - -# :Output: -# export Demo="SymbolicAI" -``` - - -## 🖥️ Interactive Shell - -`symsh` is also a regular shell program that interacts with users in the terminal emulation window. It interprets Linux, MacOS, and Windows PowerShell shell commands, and supports ANSI escape sequences. - -> ❗️**NOTE**❗️Because the colors for the default style is highly dependent on whether the theme is light or dark, they may not be displayed correctly in some terminals. You can change the default style to better fit your needs by modifying the `symsh.config.json` file in the `.symai` directory in your home directory (`~/.symai/symsh.config.json`). - -To enter an interactive shell, simply run without any additional parameters: - -```bash -$> symsh -``` - -The interactive shell uses the `python -m symai.shell` feature and runs on top of your existing terminal. - -Within the interactive shell you can use your regular shell commands and additionally use the `symsh` neuro-symbolic commands. The interactive shell supports the following commands: - -### Auto-completion -`symsh` provides path auto-completion and history auto-completion enhanced by the neuro-symbolic engine. Start typing the path or command, and `symsh` will provide you with relevant suggestions based on your input and command history. -To trigger a suggestion, press `Tab` and then `Enter`. - -![Demo usage of symsh](https://raw.githubusercontent.com/ExtensityAI/symbolicai/main/assets/images/symsh.png) - -### Query Neuro-Symbolic Model -`symsh` can interact with a language model. By beginning a command with a special character (`"`, `'`, or `` ` ``), `symsh` will treat the command as a query for a language model. - -For instance, to make a query, you can type: - -```bash -$> "What is the capital of France?" - -# :Output: -# Paris -``` -You can also type `Ctrl+Space` to treat any command as a query for a language model. - -### Pipe with Files - -The shell command in `symsh` also has the capability to interact with files using the pipe (`|`) operator. It operates like a Unix-like pipe but with a few enhancements due to the neuro-symbolic nature of `symsh`. - -Here is the basic usage of the pipe with files: - -```bash -$> "explain this file" | file_path.txt -``` -This command would instruct the AI to explain the file `file_path.txt` and consider its contents for the conversation. - -### Pipe with Commands -`symsh` can also interact with other shell commands using the pipe (`|`) operator. This allows you to execute a shell command and use its output as input to the language model along with your query. -**Basic Usage:** -```bash -$> "Your query" | command [arguments] -``` -**Example:** -Suppose you want to understand the usage of a complex command like `ffmpeg`, which has extensive help documentation. Instead of manually reading through the lengthy help output, you can ask `symsh` to summarize it for you: -```bash -$> "Summarize how to convert a video using ffmpeg" | ffmpeg -h -``` -This command runs `ffmpeg -h`, captures its output, and then asks the language model to provide a concise summary. -Similarly, if you're unsure about the options available for `grep`, which can be tedious to read through: -```bash -$> "Explain the options available for grep" | grep --help -``` -This will execute `grep --help` and pass the output to the language model, which will then explain the various options in an understandable manner. -These additions explain how to use the new feature that allows piping queries with commands, provide examples of its usage, and outline the current limitations. - -### Slicing Operation on Files -The real power of `symsh` shines through when dealing with large files. `symsh` extends the typical file interaction by allowing users to select specific sections or slices of a file. - -To use this feature, you would need to append the desired slices to the filename within square brackets `[]`. The slices should be comma-separated, and you can apply Python's indexing rules. You can specify a single line, a range of lines, or step indexing. - -Here are a few examples: - -Single line: - -```bash -$> "analyze this line" | file_path.txt[10] -``` - -Range of lines: - -```bash -# analyze lines 10 to 20 -$> "analyze this line" | file_path.txt[10:20] -``` - -Step indexing: - -```bash -# analyze lines 10 to 30 with a step size of 3 -$> "analyze this line" | file_path.txt[10:30:3] -``` - -Multi-line indexing: - -```bash -# analyze lines 10 to 30 with a step size of 3, and lines 40 to 50 -$> "analyze this line" | file_path.txt[10:30:3,20,40:50] -``` - -The above commands would read and include the specified lines from file `file_path.txt` into the ongoing conversation. - -This feature enables you to maintain highly efficient and context-thoughtful conversations with `symsh`, especially useful when dealing with large files where only a subset of content in specific locations within the file is relevant at any given moment. - -### Stateful Conversation - -The stateful_conversation feature is used for maintaining a continuing conversation with the language model. To use this feature, you have to start your commands with specific symbols in the shell: - -1. Creating a new stateful conversation: - - Use any of these three symbols at the start of your command: `!"`, `!'`, or `` !` ``. This will initialize a new stateful conversation. If there was a previously saved conversation, these commands will overwrite it. - -2. Continuing a stateful conversation: - - Use one of these three symbols at the start of your command: `."`, `.'`, or `` .` ``. The command can then be used to continue the most recent stateful conversation. If no previous conversation exists, a new one is created. - -Example: - - 1. Starting a new conversation: `!"what is your name"` - 2. Continuing the conversation: `."how old are you"` - -These commands can be used in any shell operation. Keep in mind, stateful conversations are saved and can be resumed later. The shell will save the conversation automatically if you type `exit` or `quit` to exit the interactive shell. - -Stateful conversation offers the capability to process files as well. If your command contains a pipe (`|`), the shell will treat the text after the pipe as the name of a file to add it to the conversation. - -Example: -```bash -$> !"explain this file" | my_file.txt -``` - -This command will instruct the AI to explain the file `my_file.txt` and consider its contents in the conversation. Afterwards you can continue the conversation with: - -```bash -$> ."what did you mean with ...?" -``` - -### Limitations and Notes -Currently, `symsh` supports piping your query to either a command or file(s), but **not both simultaneously**. The following cases are supported: -- **Query with Command**: `query | command [arguments]` - *Example*: - ```bash - $> "How can I use the options for tar?" | tar --help - ``` -- **Query with File(s)**: `query | file [file ...]` - *Example*: - ```bash - $> "Summarize the contents of these files" | file1.txt file2.txt - ``` -The following cases are **not supported** and will result in an error: -1. **Query with Command and File(s)**: `query | command | file` - *Not Supported*: - ```bash - $> "Process this data" | awk '{print $1}' | data.txt - ``` -2. **Query with Multiple Commands**: `query | command1 | command2` - *Not Supported*: - ```bash - $> "Explain the output" | ls -l | sort - ``` -3. **Query with File(s) and Command**: `query | file | command` - *Not Supported*: - ```bash - $> "Analyze this data" | data.txt | sort - ``` -> **Note**: If you attempt to use unsupported combinations, `symsh` will raise an error and prompt you to adjust your command accordingly. Ensure that your command outputs text to standard output (stdout). Binary outputs or commands that do not produce textual output may not work as expected. diff --git a/symbolicai-main/symbolicai-main/docs/source/TUTORIALS/chatbot.md b/symbolicai-main/symbolicai-main/docs/source/TUTORIALS/chatbot.md deleted file mode 100644 index e53d549d17c2395c5492f9a0f2e87c8303ba260d..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/TUTORIALS/chatbot.md +++ /dev/null @@ -1,83 +0,0 @@ -# Writing a Custom Chatbot - ---- - -## ⚠️ Outdated or Deprecated Documentation ⚠️ -This documentation is outdated and may not reflect the current state of the SymbolicAI library. This page might be revived or deleted entirely as we continue our development. We recommend using more modern tools that infer the documentation from the code itself, such as [DeepWiki](https://deepwiki.com/ExtensityAI/symbolicai). This will ensure you have the most accurate and up-to-date information and give you a better picture of the current state of the library. - ---- - -Click here for [interactive notebook](https://github.com/ExtensityAI/symbolicai/blob/main/notebooks/ChatBot.ipynb) - -```python -import os -import warnings -warnings.filterwarnings('ignore') -os.chdir('../') # set the working directory to the root of the project -from symai import * -from symai.components import * -from IPython.display import display -``` - -Writing a chatbot is fairly easy with our framework. All we need to do is basically derive from the ChatBot class and implement the forward method. The base class ChatBot has already some helper capabilities and context detection dictionaries. All we have to do is use the self.narrate method to instruct our chatbot to say what we want. - -Afterwards, we can use the self.context_choice method to classify the context of the user input. This is done by using a dictionary of context keywords. The self.context_choice method returns the context key that matches the user input. This key can then be used to determine the next action / condition of the chatbot. - -By creating an instance of the SymbiaChat and calling the forward method, we can start a chat with our chatbot. The forward method takes a user input and returns a chatbot response. - -See the following example: - -```python -from symai.chat import ChatBot -from symai.interfaces import Interface - - -class SymbiaChat(ChatBot): - def forward(self) -> str: - message = self.narrate('Symbia introduces herself, writes a greeting message and asks how to help.') - while True: - # query user - usr = self.input(message) - - # detect context - ctxt = self.context_choice(usr) - - if 'option 3' in ctxt: # exit - self.narrate('Symbia writes goodbye message.', end=True) - break # end chat - - elif 'option 4' in ctxt: # help - message = self.narrate('Symbia writes for each capability one sentence.', - context=self.capabilities) - - elif 'option 1' in ctxt: # chit chat - message = self.narrate('Symbia replies to the user question in a casual way.') - - elif 'option 2' in ctxt: - # detect command - option = self.capabilities_choice(usr) - - if 'option 1' in option: - q = usr.extract('user query request') - rsp = self.search(q) - message = self.narrate('Symbia replies to the user based on the online search results.', - context=rsp) - elif 'option 2' in option: - q = usr.extract('URL') - site = self.crawler(q) - site.save('tmp.html') - message = self.narrate('Symbia explains that the website is downloaded to the `tmp.html` file.') - elif 'option 3' in option: - pass - - # TODO ... -``` - -```python -from symai.chat import SymbiaChat - -chat = SymbiaChat() -chat() -``` - -The implemented chatbot can answer trivia questions, use the Google search engine to retrieve information, and download and save web pages. diff --git a/symbolicai-main/symbolicai-main/docs/source/TUTORIALS/context.md b/symbolicai-main/symbolicai-main/docs/source/TUTORIALS/context.md deleted file mode 100644 index e4093d4828d6316ed42f6514dee0eea143839c19..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/TUTORIALS/context.md +++ /dev/null @@ -1,145 +0,0 @@ -# Handling Files and Long Context Lengths - ---- - -## ⚠️ Outdated or Deprecated Documentation ⚠️ -This documentation is outdated and may not reflect the current state of the SymbolicAI library. This page might be revived or deleted entirely as we continue our development. We recommend using more modern tools that infer the documentation from the code itself, such as [DeepWiki](https://deepwiki.com/ExtensityAI/symbolicai). This will ensure you have the most accurate and up-to-date information and give you a better picture of the current state of the library. - ---- - -Click here for [interactive notebook](https://github.com/ExtensityAI/symbolicai/blob/main/notebooks/News.ipynb) - -```python -import os -import warnings -warnings.filterwarnings('ignore') -os.chdir('../') # set the working directory to the root of the project -from symai import * -from symai.components import * -from IPython.display import display -``` - -We can create contextual prompts to define the semantic operations for our model. However, this takes away a lot of our context size and since the GPT-3 context length is limited to 4097 tokens, this might quickly become a problem. Luckily we can use the `Stream` processing expression. This expression opens up a data stream and computes the remaining context length for processing the input data. Then it chunks the sequence and computes the result for each chunk. The chunks can be processed with a `Sequence` expression, that allows multiple chained operations in a sequential manner. - -In the following example we show how we can extract news from a particular website and try to recombine all individual chunks again by clustering the information among the chunks and then recombining them. This gives us a way to consolidate contextually related information and recombine them in a meaningful way. Furthermore, the clustered information can then be labeled by looking / streaming through the values within the cluster and collecting the most relevant labels. - -If we repeat this process, we now get a way of building up a hierarchical cluster with labels as entry points to allow information retrieval from our new data structure. -To make manners more concrete, lets take a look at how to build up a news generator. Let us first start by importing some pre-defined string constants. These constants are used to define how the text is processed and how we desire the output to be formatted. - -## News Generator - -```python -from examples.news import HEADER_STYLE_DESCRIPTION, HTML_TEMPLATE, HTML_STREAM_STYLE_DESCRIPTION -``` - -We sub-class the `Expression` class and define the `__init__` implementation. Similar to PyTorch we can define the graph in the `__init__` method and then call the `forward` method to compute the result. Afterwards, the data from the web URL is streamed through a `Sequence` of operations. This cleans the text from all the clutter such as `\n`, `\t`, etc. and then extracts the news from the text. -The news are then filtered and re-composed. The resulting news texts are then clustered and the clusters are labeled. The labeled clusters are then recombined to return a rendered HTML format. - -```python -class News(Expression): - """The `News` class sub-classes `Expression` and provides a way to fetch and render news from a given url. It uses a `Stream` object to process the news data, with a sequence of `Clean`, `Translate`, `Outline`, and `Compose` expressions. - It also defines a `Style` for the header, and a `Symbol` for the HTML templates. - """ - def __init__(self, url: str, pattern: str, filters: List[Expression] = [], render: bool = False, **kwargs): - """The `News` class constructor requires three arguments - `url`, `pattern` and `filters`. - * `url` is a `str` containing the url to fetch the news from. - * `pattern` is a `str` containing the name of the search key to be found on the web page. - * `filters` is a `List[Expression]` containing any additional filters that should be applied to the news data. - It defaults to an empty list if not specified. - The `News` class also has an optional `render` argument which is a `bool` indicating whether the news should be rendered. It defaults to `False` if not specified. - """ - super().__init__(**kwargs) - self.url = url - self.pattern = pattern - self.render_ = render - self.crawler = Interface('selenium') - filters = filters if isinstance(filters, List) or isinstance(filters, tuple) else [filters] - self.data_stream = Stream(Sequence( - Clean(), - Translate(), - Outline(), - *filters, - Compose(f'Compose news paragraphs. Combine only facts that belong topic-wise together:\n'), - )) - self.header_style = Style(description=HEADER_STYLE_DESCRIPTION, - libraries=['https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css', - 'https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js', - 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js']) - - self.html_template = Symbol(HTML_TEMPLATE) - self.html_template_seq = Template() - self.html_stream = Stream( - Sequence( - self.html_template_seq, - Style(description=HTML_STREAM_STYLE_DESCRIPTION) - ) - ) - - def render(self, sym: Symbol) -> Symbol: - """The `render` method takes a `Symbol` as an argument and returns a `Symbol` containing the rendered news. - It first sets the `html_template_seq` property of the `html_stream` to the result of applying the `header_style` to the `html_template`. - It then iterates through the `data_stream` and collects the strings resulting from each expression. - These strings are combined into a single `Symbol` object which is then clustered. - Finally, the `render` method applies the `html_template` to the clustered `Symbol` and returns the result. - """ - tmp = self.header_style(self.html_template) - self.html_template_seq.template_ = str(tmp) - res = '\n'.join([str(s) for s in self.html_stream(sym)]) - res = Symbol(str(tmp).replace('{{placeholder}}', res)) - return res - - def forward(self) -> Symbol: - """The `forward` method is used to fetch and process the news data. - It first calls the `fetch` method with the `url` and `pattern` arguments. - It then iterates through the `data_stream` and collects the `Symbol` object resulting from each expression. - These `Symbol` objects are then combined into a single `Symbol` object which is then mapped. - If `render` is `False`, the mapped `Symbol` is returned. Otherwise, the `render` method is called with the `Symbol` and the resulting `Symbol` is returned. - """ - res = self.crawler(url=self.url, pattern=self.pattern) - vals = [] - for news in self.data_stream(res): - vals.append(str(news)) - res = Symbol(vals).cluster() - sym = res.map() - if not self.render_: - return sym - return self.render(sym) -``` - -Here you can try the news generator: -```python -# crawling the website and creating an own website based on its facts -news = News(url='https://www.cnbc.com/cybersecurity/', - pattern='cnbc', - filters=ExcludeFilter('sentences about subscriptions, licensing, newsletter'), - render=True) -``` - -Since the generative process will evaluate multiple expression, we can use the `Trace` and `Log` classes to keep track of what is happening. - -```python -expr = Log(Trace(news)) -res = expr() -os.makedirs('results', exist_ok=True) -path = os.path.abspath('results/news.html') -res.save(path, replace=False) -``` - -## Streaming over a PDF File - -Another example is to read in a PDF file and extract the text from it to create a website based on its content. - -```python -from ..examples.paper import Paper -``` - -The process is fairly similar to the news generator. We first read in the PDF file and then stream the text through a sequence of operations. The text is then cleaned and the sentences are extracted. The sentences are then clustered and labeled. The labeled clusters are then recombined to return a rendered HTML format. - -```python -paper = Paper(path='examples/paper.pdf') -expr = Log(Trace(paper)) -res = expr(slice=(1, 1)) -os.makedirs('results', exist_ok=True) -path = os.path.abspath('results/news.html') -res.save(path, replace=False) -``` diff --git a/symbolicai-main/symbolicai-main/docs/source/TUTORIALS/data_query.md b/symbolicai-main/symbolicai-main/docs/source/TUTORIALS/data_query.md deleted file mode 100644 index 5e41bdb84c0a75d158f3a73fade963d201710207..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/TUTORIALS/data_query.md +++ /dev/null @@ -1,121 +0,0 @@ -# Querying Data with SQL - ---- - -## ⚠️ Outdated or Deprecated Documentation ⚠️ -This documentation is outdated and may not reflect the current state of the SymbolicAI library. This page might be revived or deleted entirely as we continue our development. We recommend using more modern tools that infer the documentation from the code itself, such as [DeepWiki](https://deepwiki.com/ExtensityAI/symbolicai). This will ensure you have the most accurate and up-to-date information and give you a better picture of the current state of the library. - ---- - -Click here for [interactive notebook](https://github.com/ExtensityAI/symbolicai/blob/main/notebooks/Queries.ipynb) - -```python -import os -import warnings -warnings.filterwarnings('ignore') -print(os.getcwd()) -from symai import * -from IPython.display import display -from examples.sql import SQL -sql = SQL() -``` - -The `SQL` expression is defined and passes as a global context the syntax of the SQL language. The SQL expression is then used to generate queries based on the given context. We can then use the generated queries to get data from a database. -The following query is sent to the neural computation engine and creates a query based on the given context: -```python -val = None -def _fun(x): - global val - val = x -Symbol._metadata.input_handler = _fun -``` - -```python -Symbol('I have this class').translate('German') -``` - -```python -q = sql('Select all users above the age of 30 from the Members table.'); -display(q) # SELECT * FROM Members WHERE age > 30 -``` - -We can now try to further manipulate the result by asking the model to incorporate additional information, such as filtering to a specific time range: - -```python -res = q << 'and limit the query to the last 10 minutes' -display(res) # SELECT * FROM Members WHERE age > 30 AND timestamp > NOW() - INTERVAL 10 MINUTE -``` - -We can also try to remove unwanted fields from the generated query. Notice how the model tries to remove not only the given statement but attributes associated with them: - -```python -res -= ' AND ...' -display(res) # SELECT * FROM Members WHERE age > 30 -``` - -And we can now even convert our query to other familiar domain specific languages, such as `SQL` or `ActiveRecord`: - -```python -sql_res = res.convert("ActiveRecord") -display(sql_res) # Members.where("age > ?", 30) -``` - -To wrap things up, we might want to go back full circle and ask the model to generate again the explanation based on the given query: - -```python -answer_doc = res.query("What does this query do?") -display(answer_doc) -# The given SQL query retrieves all records from a table named `Members` where two conditions are met: -# 1. The `age` column of a member record must be greater than 30. -# 2. The `timestamp` column of a member record must be more recent than (or within) -# the last 10 minutes from the current time. More specifically: - `SELECT *` indicates that it will -# fetch all columns for the qualifying rows. - `FROM Members` specifies the table from which to fetch -# the data. - `WHERE` introduces the conditions to filter which rows should be returned. - `age > 30` -# filters the records to only include those where the age column value is greater than 30. - `AND` -# combines multiple conditions, meaning a record must meet all the specified conditions to be included. -# - `timestamp > NOW() - INTERVAL 10 MINUTE` checks for records with a timestamp within the last 10 -# minutes. `NOW()` is a function that returns the current datetime. `INTERVAL 10 MINUTE` specifies a -# time interval of 10 minutes. By subtracting this interval from the current time, the query creates a -# datetime value that is 10 minutes before now. The condition `timestamp >` selects all records where -# the `timestamp` is more recent than that calculated time. This query would be useful for identifying -# active, older members (above 30 years old) who have engaged with the system or performed an action -# that updates their `timestamp` within the last 10 minutes. -``` - -Ask it in natural language to modify the query: - -```python -answer = res.query("How can you limit the number of results to 30 for an SQL query?") -display(answer) -# To limit the number of results to 30 for an SQL query, you can use the `LIMIT` clause in your SQL -# statement. The `LIMIT` clause restricts the number of rows returned by the query. Here's how you modify -# your given SQL query to limit the results to 30: ```sql SELECT * FROM Members WHERE age > 30 LIMIT 30;``` -# This query will retrieve a maximum of 30 records from the 'Members' table where the 'age' column value is greater than 30. -``` - -Even translate the explanation to a different language on the fly: - -```python -locale = Symbol(answer_doc).translate('German') -display(locale) -``` - -Fixing the query on the fly if something goes wrong or the user quickly wants to adapt a query: - -```python -sql.adapt(context="""Explanation: Never allow SELECT *, always use LIMIT to a max of x <= 50 entries, where x is the user specified limit.""") -``` - -```python -res = sql('Select all users above the age of 30 from the Members table.') -display(res) # SELECT * FROM Members WHERE age > 30 LIMIT 50 -``` - -```python -sql.clear() -``` - -```python -res = sql('Select all users above the age of 30 from the Members table.') -display(res) # SELECT * FROM Members WHERE age > 30 -``` diff --git a/symbolicai-main/symbolicai-main/docs/source/TUTORIALS/video_tutorials.md b/symbolicai-main/symbolicai-main/docs/source/TUTORIALS/video_tutorials.md deleted file mode 100644 index 6676c015b98015e6b160e666b61da7a2da4eebda..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/docs/source/TUTORIALS/video_tutorials.md +++ /dev/null @@ -1,17 +0,0 @@ -# Video Tutorials - ---- - -## ⚠️ Outdated or Deprecated Documentation ⚠️ -This documentation is outdated and may not reflect the current state of the SymbolicAI library. This page might be revived or deleted entirely as we continue our development. We recommend using more modern tools that infer the documentation from the code itself, such as [DeepWiki](https://deepwiki.com/ExtensityAI/symbolicai). This will ensure you have the most accurate and up-to-date information and give you a better picture of the current state of the library. - ---- - -| Date | Title | Video | -| ---- | ---- | ---- | -| 2nd Dec. 2023 | Use ChatGPT and off-the-shelf RAG on Terminal/Command Prompt/Shell | [![Use ChatGPT and off-the-shelf RAG on Terminal/Command Prompt/Shell](https://raw.githubusercontent.com/ExtensityAI/symbolicai/main/assets/images/vid6.png)](https://youtu.be/RJ6i_b91nQE?si=jZR4LJRZQZVAm4MA) | -| 21st Nov. 2023 | Virtual Persona from Documents, Multi-Agent Chat, Text-to-Speech to hear your Personas | [![Virtual Persona from Documents, Multi-Agent Chat, Text-to-Speech to hear your Personas](https://raw.githubusercontent.com/ExtensityAI/symbolicai/main/assets/images/vid5.png)](https://www.youtube.com/watch?v=-o2315T9348) | -| 1st Aug. 2023 | Automatic Retrieval Augmented Generation, Multimodal Inputs, User Packages | [![Automatic Retrieval Augmented Generation, Multimodal Inputs, User Packages](https://raw.githubusercontent.com/ExtensityAI/symbolicai/main/assets/images/vid4.png)](https://www.youtube.com/watch?v=0AqB6SEvRqo) | -| 22nd July 2023 | ChatBot In-Depth Demonstration (Tool Use and Iterative Processing) | [![ChatBot In-Depth Demonstration (Tool Use and Iterative Processing)](https://raw.githubusercontent.com/ExtensityAI/symbolicai/main/assets/images/vid3.png)](https://www.youtube.com/watch?v=R46SskmmrCE) | -| 1st July 2023 | Symbols, Operations, Expressions, LLM-based functions! | [![Symbols, Operations, Expressions, LLM-based functions!](https://raw.githubusercontent.com/ExtensityAI/symbolicai/main/assets/images/vid2.png)](https://www.youtube.com/watch?v=Ch9ygW62A34) | -| 9th June 2023 | The future is neuro-symbolic: Expressiveness of ChatGPT and generalizability of symbols | [![The future is neuro-symbolic: Expressiveness of ChatGPT and generalizability of symbols](https://raw.githubusercontent.com/ExtensityAI/symbolicai/main/assets/images/vid1.png)](https://www.youtube.com/watch?v=RW_7JdXvbRA) | diff --git a/symbolicai-main/symbolicai-main/environment.yml b/symbolicai-main/symbolicai-main/environment.yml deleted file mode 100644 index b5508008cad524b16fd334c611fa33284bad5609..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/environment.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: symai - -channels: - - default - - conda-forge - - pytorch - - nvidia - -dependencies: - - python - - setuptools - - toml - - natsort - - numpy - - tqdm - - python-box - - scikit-learn - - pytorch - - pytorch-cuda - - torchvision - - torchaudio - - pyyaml - - transformers - - openai - - pypdf - - ipython - - beautifulsoup4 - - selenium - - rpyc - - accelerate - - sentencepiece - - webdriver-manager - - pandas - - tika - - pip - - paramiko # For SSH protocol operations - - docker-py # Docker SDK for Python - - - pip: - - sympy - - symbolicai[all] diff --git a/symbolicai-main/symbolicai-main/examples/contracts.ipynb b/symbolicai-main/symbolicai-main/examples/contracts.ipynb deleted file mode 100644 index ebf7db0a71509684c34664e02c3809385f066449..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/examples/contracts.ipynb +++ /dev/null @@ -1,599 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "id": "a72df661-ea3c-4cd8-9eab-ce9ca4c87ab8", - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/Users/futurisold/miniconda3/envs/symai/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", - " from .autonotebook import tqdm as notebook_tqdm\n" - ] - } - ], - "source": [ - "# ──────────────────────────────────────────────────────────────\n", - "# Standard library │\n", - "# ──────────────────────────────────────────────────────────────\n", - "from typing import List, Optional\n", - "\n", - "from pydantic import Field\n", - "\n", - "# ──────────────────────────────────────────────────────────────\n", - "# SymbolicAI core │\n", - "# ──────────────────────────────────────────────────────────────\n", - "from symai import Expression # Base class for your LLM “operators”\n", - "from symai.models import LLMDataModel # Thin Pydantic wrapper w/ LLM hints\n", - "from symai.strategy import contract # The Design-by-Contract decorator" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "817cc004-2782-4239-9ffd-27f634e00cee", - "metadata": {}, - "outputs": [], - "source": [ - "# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n", - "# 1. Data models ▬\n", - "# – clear structure + rich Field descriptions power ▬\n", - "# validation, automatic prompt templating & remedies ▬\n", - "# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n", - "\n", - "class Document(LLMDataModel):\n", - " \"\"\"Represents an entire document in the tiny in-memory corpus.\"\"\"\n", - " id: str = Field(description=\"Unique identifier of the document.\")\n", - " content: str = Field(description=\"The full raw text of the document.\")\n", - "\n", - "\n", - "class DocSnippet(LLMDataModel):\n", - " \"\"\"\n", - " Exact passage taken *verbatim* from a Document.\n", - " We store the `doc_id` so the answer can cite its source.\n", - " \"\"\"\n", - " doc_id: str = Field(description=\"ID of the document the snippet comes from.\")\n", - " snippet: str = Field(description=\"A short excerpt supporting the answer.\")\n", - "\n", - "\n", - "class MultiDocQAInput(LLMDataModel):\n", - " \"\"\"\n", - " The *input* to the contract call:\n", - " • the user’s natural-language question\n", - " • the corpus it may answer from\n", - " • a caller-specified upper bound on how many snippets can be cited\n", - " \"\"\"\n", - " query: str = Field(description=\"User question in plain English.\")\n", - " documents: List[Document] = Field(description=\"Corpus to search for answers.\")\n", - " max_snippets: Optional[int] = Field(\n", - " default=3,\n", - " ge=1,\n", - " le=10,\n", - " description=\"Max number of snippets the agent may cite (defaults to 3).\",\n", - " )\n", - "\n", - "\n", - "class IntermediateRetrieved(LLMDataModel):\n", - " \"\"\"\n", - " Returned by `act()`: lightweight retrieval result that will be fed to\n", - " the LLM so it can see relevant sentences without scanning whole docs.\n", - " \"\"\"\n", - " query: str = Field(description=\"The original question from the user.\")\n", - " top_docs: List[Document] = Field(description=\"Top-k most relevant documents.\")\n", - " selected_sentences: List[str] = Field(\n", - " description=\"Sentences deemed most relevant to the query.\"\n", - " )\n", - " target_snippet_count: int = Field(\n", - " description=\"Upper bound on evidence snippets (copied from input).\"\n", - " )\n", - "\n", - "\n", - "class AnswerWithEvidence(LLMDataModel):\n", - " \"\"\"\n", - " Final object returned to the **caller** (and validated by `post`).\n", - " \"\"\"\n", - " answer: str = Field(description=\"Concise, stand-alone answer.\")\n", - " evidence: List[DocSnippet] = Field(description=\"Cited supporting passages.\")\n", - " coverage_score: float = Field(\n", - " ge=0.0,\n", - " le=1.0,\n", - " description=(\n", - " \"LLM-estimated fraction of answer that is directly supported by the \"\n", - " \"evidence (0 = no support, 1 = fully supported).\"\n", - " ),\n", - " )\n", - "\n", - "# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n", - "# 2. The contracted class ▬\n", - "# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n", - "@contract(\n", - " # ── Remedies ─────────────────────────────────────────── #\n", - " pre_remedy=True, # Try to fix bad inputs automatically\n", - " post_remedy=True, # Try to fix bad LLM outputs automatically\n", - " accumulate_errors=True, # Feed history of errors to each retry\n", - " verbose=True, # Log internal steps (see `symai.strategy` logger)\n", - " remedy_retry_params=dict(tries=3, delay=0.4, max_delay=4.0,\n", - " jitter=0.15, backoff=1.8, graceful=False),\n", - ")\n", - "class MultiDocQAgent(Expression):\n", - " \"\"\"\n", - " High-level behaviour:\n", - " 1. `pre` – sanity-check query & docs\n", - " 2. `act` – *retrieve* relevant sentences, mutate state\n", - " 3. LLM – generate AnswerWithEvidence (handled by SymbolicAI engine)\n", - " 4. `post` – ensure answer & evidence meet semantic rules\n", - " 5. `forward`\n", - " • if contract succeeded → return validated LLM object\n", - " • else → graceful fallback answer\n", - " \"\"\"\n", - "\n", - " # ───────────────────────── init ───────────────────────── #\n", - " def __init__(self, min_coverage: float = 0.55, *args, **kwargs):\n", - " super().__init__(*args, **kwargs)\n", - " self.min_coverage = min_coverage # threshold for `post`\n", - " self.interaction_log: list[dict] = [] # keeps a history of queries\n", - "\n", - " # ───────────────────────── prompt ─────────────────────── #\n", - " @property\n", - " def prompt(self) -> str:\n", - " \"\"\"\n", - " A *static* description of what the LLM must do.\n", - " Braces {{like_this}} will be replaced with fields from\n", - " the object produced by `_validate_input`/`_act`.\n", - " \"\"\"\n", - " return (\n", - " \"You are an expert research assistant.\\n\"\n", - " \"Given a QUESTION and a set of RELEVANT_SENTENCES, write a concise \"\n", - " \"answer. Cite every passage you use exactly as `(Doc )`. \"\n", - " \"Respond with a JSON object that fits the AnswerWithEvidence schema.\"\n", - " )\n", - "\n", - " # ───────────────────────── pre ────────────────────────── #\n", - " def pre(self, input: MultiDocQAInput) -> bool:\n", - " \"\"\"\n", - " Guard-clauses before we even *touch* the LLM.\n", - " Raise ValueError with human-readable messages – they become corrective\n", - " prompts if `pre_remedy=True`.\n", - " \"\"\"\n", - " if not input.query.strip():\n", - " raise ValueError(\"The query must not be empty.\")\n", - " if not input.documents:\n", - " raise ValueError(\"You must supply at least one document.\")\n", - " return True # all good\n", - "\n", - " # ───────────────────────── act ────────────────────────── #\n", - " def act(self, input: MultiDocQAInput, **kwargs) -> IntermediateRetrieved:\n", - " \"\"\"\n", - " Lightweight pseudo-retrieval.\n", - "\n", - " Steps:\n", - " • score each doc by term overlap with the query\n", - " • keep top-k (k ≤ 3)\n", - " • within each, take two most overlapping sentences\n", - " • log the interaction for later analytics\n", - " \"\"\"\n", - " k = min(3, len(input.documents))\n", - " query_terms = {t.lower() for t in input.query.split()}\n", - "\n", - " # Score documents by *crude* term overlap\n", - " scored_docs = []\n", - " for doc in input.documents:\n", - " overlap = sum(t in query_terms for t in doc.content.lower().split())\n", - " scored_docs.append((overlap, doc))\n", - " scored_docs.sort(reverse=True, key=lambda x: x[0])\n", - "\n", - " top_docs = [doc for _, doc in scored_docs[:k]]\n", - "\n", - " # Extract at most 2 high-overlap sentences from each top doc\n", - " selected_sentences: list[str] = []\n", - " for doc in top_docs:\n", - " sentences = [s.strip() for s in doc.content.split(\".\") if s.strip()]\n", - " sentences.sort(\n", - " reverse=True,\n", - " key=lambda s: sum(t in query_terms for t in s.lower().split()),\n", - " )\n", - " selected_sentences.extend(sentences[:2])\n", - "\n", - " # Record what we did (just for analytics / debugging)\n", - " self.interaction_log.append(\n", - " {\n", - " \"query\": input.query,\n", - " \"num_docs\": len(input.documents),\n", - " \"top_doc_ids\": [d.id for d in top_docs],\n", - " }\n", - " )\n", - "\n", - " # Return a *different* LLMDataModel; this becomes the\n", - " # `current_input` for the output-validation phase.\n", - " return IntermediateRetrieved(\n", - " query=input.query,\n", - " top_docs=top_docs,\n", - " selected_sentences=selected_sentences,\n", - " target_snippet_count=input.max_snippets or 3,\n", - " )\n", - "\n", - " # ───────────────────────── post ───────────────────────── #\n", - " def post(self, output: AnswerWithEvidence) -> bool:\n", - " \"\"\"\n", - " Semantic guarantees:\n", - " • non-empty answer\n", - " • coverage ≥ threshold\n", - " • high-coverage → must actually cite evidence\n", - " • evidence list ≤ `target_snippet_count` learned in `act`\n", - " Any violation ⇒ raise ValueError (triggers post-remedy or failure).\n", - " \"\"\"\n", - " if not output.answer.strip():\n", - " raise ValueError(\"Answer text is empty.\")\n", - "\n", - " # coverage gate\n", - " if output.coverage_score < self.min_coverage:\n", - " raise ValueError(\n", - " f\"Coverage score {output.coverage_score:.2f} \"\n", - " f\"is below the minimum {self.min_coverage:.2f}.\"\n", - " )\n", - "\n", - " # If it claims high coverage but provides no evidence, that's fishy\n", - " if output.coverage_score >= 0.8 and not output.evidence:\n", - " raise ValueError(\n", - " \"High coverage claims require at least one evidence snippet.\"\n", - " )\n", - "\n", - " # Enforce caller’s snippet bound (act stored it on self._current_input)\n", - " max_allowed = getattr(self, \"_current_input\", None)\n", - " if (\n", - " isinstance(max_allowed, IntermediateRetrieved)\n", - " and output.evidence\n", - " and len(output.evidence) > max_allowed.target_snippet_count\n", - " ):\n", - " raise ValueError(\n", - " f\"Too many snippets ({len(output.evidence)}), \"\n", - " f\"maximum allowed is {max_allowed.target_snippet_count}.\"\n", - " )\n", - "\n", - " return True # all checks passed\n", - "\n", - " # ───────────────────────── forward ────────────────────── #\n", - " def forward(self, input: MultiDocQAInput, **kwargs) -> AnswerWithEvidence:\n", - " \"\"\"\n", - " ALWAYS executed (even if contract failed).\n", - "\n", - " Success path → return the LLM-validated object (`self.contract_result`)\n", - " Failure path → build a polite fallback answer that still matches schema\n", - " \"\"\"\n", - " # ── happy path ─────────────────────────────────────── #\n", - " if self.contract_successful and self.contract_result:\n", - " return self.contract_result\n", - "\n", - " # ── fallback (contract failed) ─────────────────────── #\n", - " first_doc = input.documents[0]\n", - " first_sentence = first_doc.content.split(\".\")[0][:300] # keep it short\n", - " return AnswerWithEvidence(\n", - " answer=(\n", - " \"I’m not confident enough to answer precisely. \"\n", - " \"Please re-phrase the question or provide more documents.\"\n", - " ),\n", - " evidence=[DocSnippet(doc_id=first_doc.id, snippet=first_sentence)],\n", - " coverage_score=0.0,\n", - " )" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "74261d3f-e9b5-4cc9-a94e-885c514195c9", - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "\u001b[32m2025-06-26 18:35:47.031\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36m__init__\u001b[0m:\u001b[36m531\u001b[0m - \u001b[1mInitializing contract...\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:47.031\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36m__init__\u001b[0m:\u001b[36m541\u001b[0m - \u001b[1mContract initialization complete!\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:47.032\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36mwrapped_forward\u001b[0m:\u001b[36m546\u001b[0m - \u001b[1mStarting contract execution...\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:47.032\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36m_validate_input\u001b[0m:\u001b[36m413\u001b[0m - \u001b[1mStarting input validation...\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:47.032\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36m_validate_input\u001b[0m:\u001b[36m415\u001b[0m - \u001b[1mValidating pre-conditions with remedy...\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:47.032\u001b[0m | \u001b[32m\u001b[1mSUCCESS \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36m_validate_input\u001b[0m:\u001b[36m423\u001b[0m - \u001b[32m\u001b[1mPre-condition validation successful!\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:47.033\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36m_act\u001b[0m:\u001b[36m502\u001b[0m - \u001b[1mExecuting 'act' method on MultiDocQAgent…\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:47.033\u001b[0m | \u001b[32m\u001b[1mSUCCESS \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36m_act\u001b[0m:\u001b[36m523\u001b[0m - \u001b[32m\u001b[1m'act' method executed successfully!\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:47.033\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36m_validate_output\u001b[0m:\u001b[36m448\u001b[0m - \u001b[1mStarting output validation...\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:47.033\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36m_validate_output\u001b[0m:\u001b[36m454\u001b[0m - \u001b[1mGetting a valid output type...\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:47.033\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36mforward\u001b[0m:\u001b[36m291\u001b[0m - \u001b[1mInitializing validation…\u001b[0m\n" - ] - }, - { - "data": { - "text/html": [ - "
╭──────────────────────────────────────────────────── Prompt ─────────────────────────────────────────────────────╮\n",
-       "│                                                                                                                 │\n",
-       "│  You are an expert research assistant.                                                                          │\n",
-       "│  Given a QUESTION and a set of RELEVANT_SENTENCES, write a concise answer.  Cite every passage you use exactly  │\n",
-       "│  as `(Doc <ID>)`.  Respond with a JSON object that fits the AnswerWithEvidence schema.                          │\n",
-       "│                                                                                                                 │\n",
-       "╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
-       "
\n" - ], - "text/plain": [ - "\u001b[36m╭─\u001b[0m\u001b[36m───────────────────────────────────────────────────\u001b[0m\u001b[36m Prompt \u001b[0m\u001b[36m────────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230mYou are an expert research assistant.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230mGiven a QUESTION and a set of RELEVANT_SENTENCES, write a concise answer. Cite every passage you use exactly\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230mas `(Doc )`. Respond with a JSON object that fits the AnswerWithEvidence schema.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/html": [ - "
╭────────────────────────────────────────── Input data model ───────────────────────────────────────────╮\n",
-       "│                                                                                                       │\n",
-       "│  [[Schema]]                                                                                           │\n",
-       "│  - \"query\" (string, required): The original question from the user.                                   │\n",
-       "│  - \"top_docs\" (array of nested object (Document), required): Top-k most relevant documents.           │\n",
-       "│    - Nested fields:                                                                                   │\n",
-       "│    - \"id\" (string, required): Unique identifier of the document.                                      │\n",
-       "│    - \"content\" (string, required): The full raw text of the document.                                 │\n",
-       "│  - \"selected_sentences\" (array of string, required): Sentences deemed most relevant to the query.     │\n",
-       "│  - \"target_snippet_count\" (integer, required): Upper bound on evidence snippets (copied from input).  │\n",
-       "│                                                                                                       │\n",
-       "│  [[Definitions]]                                                                                      │\n",
-       "│  - Document:                                                                                          │\n",
-       "│    - \"id\" (string, required): Unique identifier of the document.                                      │\n",
-       "│    - \"content\" (string, required): The full raw text of the document.                                 │\n",
-       "│                                                                                                       │\n",
-       "╰───────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
-       "
\n" - ], - "text/plain": [ - "\u001b[36m╭─\u001b[0m\u001b[36m─────────────────────────────────────────\u001b[0m\u001b[36m Input data model \u001b[0m\u001b[36m──────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m[[Schema]]\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m- \"query\" (string, required): The original question from the user.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m- \"top_docs\" (array of nested object (Document), required): Top-k most relevant documents.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m - Nested fields:\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m - \"id\" (string, required): Unique identifier of the document.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m - \"content\" (string, required): The full raw text of the document.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m- \"selected_sentences\" (array of string, required): Sentences deemed most relevant to the query.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m- \"target_snippet_count\" (integer, required): Upper bound on evidence snippets (copied from input).\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m[[Definitions]]\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m- Document:\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m - \"id\" (string, required): Unique identifier of the document.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m - \"content\" (string, required): The full raw text of the document.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m╰───────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/html": [ - "
╭─────────────────────────────────────────────── Output data model ───────────────────────────────────────────────╮\n",
-       "│                                                                                                                 │\n",
-       "│  [[Schema]]                                                                                                     │\n",
-       "│  - \"answer\" (string, required): Concise, stand-alone answer.                                                    │\n",
-       "│  - \"evidence\" (array of nested object (DocSnippet), required): Cited supporting passages.                       │\n",
-       "│    - Nested fields:                                                                                             │\n",
-       "│    - \"doc_id\" (string, required): ID of the document the snippet comes from.                                    │\n",
-       "│    - \"snippet\" (string, required): A short excerpt supporting the answer.                                       │\n",
-       "│  - \"coverage_score\" (number, required): LLM-estimated fraction of answer that is directly supported by the      │\n",
-       "│  evidence (0 = no support, 1 = fully supported).                                                                │\n",
-       "│                                                                                                                 │\n",
-       "│  [[Definitions]]                                                                                                │\n",
-       "│  - DocSnippet:                                                                                                  │\n",
-       "│    - \"doc_id\" (string, required): ID of the document the snippet comes from.                                    │\n",
-       "│    - \"snippet\" (string, required): A short excerpt supporting the answer.                                       │\n",
-       "│                                                                                                                 │\n",
-       "╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
-       "
\n" - ], - "text/plain": [ - "\u001b[36m╭─\u001b[0m\u001b[36m──────────────────────────────────────────────\u001b[0m\u001b[36m Output data model \u001b[0m\u001b[36m──────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m[[Schema]]\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m- \"answer\" (string, required): Concise, stand-alone answer.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m- \"evidence\" (array of nested object (DocSnippet), required): Cited supporting passages.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m - Nested fields:\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m - \"doc_id\" (string, required): ID of the document the snippet comes from.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m - \"snippet\" (string, required): A short excerpt supporting the answer.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m- \"coverage_score\" (number, required): LLM-estimated fraction of answer that is directly supported by the \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230mevidence (0 = no support, 1 = fully supported).\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m[[Definitions]]\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m- DocSnippet:\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m - \"doc_id\" (string, required): ID of the document the snippet comes from.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m - \"snippet\" (string, required): A short excerpt supporting the answer.\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m│\u001b[0m\u001b[38;2;240;238;230m \u001b[0m\u001b[36m│\u001b[0m\n", - "\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - "\u001b[32m2025-06-26 18:35:50.420\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36mforward\u001b[0m:\u001b[36m305\u001b[0m - \u001b[1mPrepared 3 remedy seeds for validation attempts…\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:50.422\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36mforward\u001b[0m:\u001b[36m310\u001b[0m - \u001b[1mAttempt 1/3: Attempting validation…\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:50.422\u001b[0m | \u001b[32m\u001b[1mSUCCESS \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36mforward\u001b[0m:\u001b[36m360\u001b[0m - \u001b[32m\u001b[1mValidation completed successfully!\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:50.425\u001b[0m | \u001b[32m\u001b[1mSUCCESS \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36m_validate_output\u001b[0m:\u001b[36m461\u001b[0m - \u001b[32m\u001b[1mType successfully created!\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:50.426\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36m_validate_output\u001b[0m:\u001b[36m464\u001b[0m - \u001b[1mValidating post-conditions with remedy...\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:50.427\u001b[0m | \u001b[32m\u001b[1mSUCCESS \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36m_validate_output\u001b[0m:\u001b[36m472\u001b[0m - \u001b[32m\u001b[1mPost-condition validation successful!\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:50.427\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36mwrapped_forward\u001b[0m:\u001b[36m596\u001b[0m - \u001b[1mExecuting original forward method...\u001b[0m\n", - "\u001b[32m2025-06-26 18:35:50.429\u001b[0m | \u001b[32m\u001b[1mSUCCESS \u001b[0m | \u001b[36msymai.strategy\u001b[0m:\u001b[36mwrapped_forward\u001b[0m:\u001b[36m624\u001b[0m - \u001b[32m\u001b[1mContract validation successful!\u001b[0m\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "Answer:\n", - " Vector databases are useful for semantic search because they store embeddings of documents and allow for the quick retrieval of text that is semantically similar to a query vector, which enables high-quality semantic search (Doc B2).\n", - "\n", - "Coverage: 1.0\n", - "\n", - "Evidence:\n", - " • (Doc B2) Vector databases store embeddings of documents.\n", - " • (Doc B2) They let users quickly retrieve text that is semantically similar to a query vector, enabling high-quality semantic search.\n" - ] - }, - { - "data": { - "text/html": [ - "
\n",
-       "\n",
-       "
\n" - ], - "text/plain": [ - "\n", - "\n" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/html": [ - "
                              Contract Execution Summary (1 Forward Calls)                              \n",
-       "┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━┓\n",
-       "┃ Operation         ┃ Count ┃ Total Time (s) ┃ Mean (s) ┃ Std Dev (s) ┃ Min (s) ┃ Max (s) ┃ % of Total ┃\n",
-       "┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━┩\n",
-       "│ Input Validation  │     1 │          0.000 │    0.000 │       0.000 │   0.000 │   0.000 │       0.0% │\n",
-       "│ Act Execution     │     1 │          0.000 │    0.000 │       0.000 │   0.000 │   0.000 │       0.0% │\n",
-       "│ Output Validation │     1 │          3.392 │    3.392 │       0.000 │   3.392 │   3.392 │      99.9% │\n",
-       "│ Forward Execution │     1 │          0.000 │    0.000 │       0.000 │   0.000 │   0.000 │       0.0% │\n",
-       "│ Overhead          │     1 │          0.005 │    0.005 │       0.000 │   0.000 │   0.000 │       0.1% │\n",
-       "│ Total Execution   │   N/A │          3.397 │    3.397 │       0.000 │   3.397 │   3.397 │     100.0% │\n",
-       "└───────────────────┴───────┴────────────────┴──────────┴─────────────┴─────────┴─────────┴────────────┘\n",
-       "
\n" - ], - "text/plain": [ - "\u001b[3m Contract Execution Summary (1 Forward Calls) \u001b[0m\n", - "┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━┓\n", - "┃\u001b[1m \u001b[0m\u001b[1mOperation \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mCount\u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mTotal Time (s)\u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mMean (s)\u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mStd Dev (s)\u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mMin (s)\u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mMax (s)\u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1m% of Total\u001b[0m\u001b[1m \u001b[0m┃\n", - "┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━┩\n", - "│\u001b[36m \u001b[0m\u001b[36mInput Validation \u001b[0m\u001b[36m \u001b[0m│\u001b[34m \u001b[0m\u001b[34m 1\u001b[0m\u001b[34m \u001b[0m│\u001b[32m \u001b[0m\u001b[32m 0.000\u001b[0m\u001b[32m \u001b[0m│\u001b[33m \u001b[0m\u001b[33m 0.000\u001b[0m\u001b[33m \u001b[0m│\u001b[35m \u001b[0m\u001b[35m 0.000\u001b[0m\u001b[35m \u001b[0m│\u001b[31m \u001b[0m\u001b[31m 0.000\u001b[0m\u001b[31m \u001b[0m│\u001b[31m \u001b[0m\u001b[31m 0.000\u001b[0m\u001b[31m \u001b[0m│\u001b[36m \u001b[0m\u001b[36m 0.0%\u001b[0m\u001b[36m \u001b[0m│\n", - "│\u001b[36m \u001b[0m\u001b[36mAct Execution \u001b[0m\u001b[36m \u001b[0m│\u001b[34m \u001b[0m\u001b[34m 1\u001b[0m\u001b[34m \u001b[0m│\u001b[32m \u001b[0m\u001b[32m 0.000\u001b[0m\u001b[32m \u001b[0m│\u001b[33m \u001b[0m\u001b[33m 0.000\u001b[0m\u001b[33m \u001b[0m│\u001b[35m \u001b[0m\u001b[35m 0.000\u001b[0m\u001b[35m \u001b[0m│\u001b[31m \u001b[0m\u001b[31m 0.000\u001b[0m\u001b[31m \u001b[0m│\u001b[31m \u001b[0m\u001b[31m 0.000\u001b[0m\u001b[31m \u001b[0m│\u001b[36m \u001b[0m\u001b[36m 0.0%\u001b[0m\u001b[36m \u001b[0m│\n", - "│\u001b[36m \u001b[0m\u001b[36mOutput Validation\u001b[0m\u001b[36m \u001b[0m│\u001b[34m \u001b[0m\u001b[34m 1\u001b[0m\u001b[34m \u001b[0m│\u001b[32m \u001b[0m\u001b[32m 3.392\u001b[0m\u001b[32m \u001b[0m│\u001b[33m \u001b[0m\u001b[33m 3.392\u001b[0m\u001b[33m \u001b[0m│\u001b[35m \u001b[0m\u001b[35m 0.000\u001b[0m\u001b[35m \u001b[0m│\u001b[31m \u001b[0m\u001b[31m 3.392\u001b[0m\u001b[31m \u001b[0m│\u001b[31m \u001b[0m\u001b[31m 3.392\u001b[0m\u001b[31m \u001b[0m│\u001b[36m \u001b[0m\u001b[36m 99.9%\u001b[0m\u001b[36m \u001b[0m│\n", - "│\u001b[36m \u001b[0m\u001b[36mForward Execution\u001b[0m\u001b[36m \u001b[0m│\u001b[34m \u001b[0m\u001b[34m 1\u001b[0m\u001b[34m \u001b[0m│\u001b[32m \u001b[0m\u001b[32m 0.000\u001b[0m\u001b[32m \u001b[0m│\u001b[33m \u001b[0m\u001b[33m 0.000\u001b[0m\u001b[33m \u001b[0m│\u001b[35m \u001b[0m\u001b[35m 0.000\u001b[0m\u001b[35m \u001b[0m│\u001b[31m \u001b[0m\u001b[31m 0.000\u001b[0m\u001b[31m \u001b[0m│\u001b[31m \u001b[0m\u001b[31m 0.000\u001b[0m\u001b[31m \u001b[0m│\u001b[36m \u001b[0m\u001b[36m 0.0%\u001b[0m\u001b[36m \u001b[0m│\n", - "│\u001b[1;34m \u001b[0m\u001b[1;34mOverhead \u001b[0m\u001b[1;34m \u001b[0m│\u001b[1;34m \u001b[0m\u001b[1;34m 1\u001b[0m\u001b[1;34m \u001b[0m│\u001b[1;34m \u001b[0m\u001b[1;34m 0.005\u001b[0m\u001b[1;34m \u001b[0m│\u001b[1;34m \u001b[0m\u001b[1;34m 0.005\u001b[0m\u001b[1;34m \u001b[0m│\u001b[1;34m \u001b[0m\u001b[1;34m 0.000\u001b[0m\u001b[1;34m \u001b[0m│\u001b[1;34m \u001b[0m\u001b[1;34m 0.000\u001b[0m\u001b[1;34m \u001b[0m│\u001b[1;34m \u001b[0m\u001b[1;34m 0.000\u001b[0m\u001b[1;34m \u001b[0m│\u001b[1;34m \u001b[0m\u001b[1;34m 0.1%\u001b[0m\u001b[1;34m \u001b[0m│\n", - "│\u001b[1;35m \u001b[0m\u001b[1;35mTotal Execution \u001b[0m\u001b[1;35m \u001b[0m│\u001b[1;35m \u001b[0m\u001b[1;35m N/A\u001b[0m\u001b[1;35m \u001b[0m│\u001b[1;35m \u001b[0m\u001b[1;35m 3.397\u001b[0m\u001b[1;35m \u001b[0m│\u001b[1;35m \u001b[0m\u001b[1;35m 3.397\u001b[0m\u001b[1;35m \u001b[0m│\u001b[1;35m \u001b[0m\u001b[1;35m 0.000\u001b[0m\u001b[1;35m \u001b[0m│\u001b[1;35m \u001b[0m\u001b[1;35m 3.397\u001b[0m\u001b[1;35m \u001b[0m│\u001b[1;35m \u001b[0m\u001b[1;35m 3.397\u001b[0m\u001b[1;35m \u001b[0m│\u001b[1;35m \u001b[0m\u001b[1;35m 100.0%\u001b[0m\u001b[1;35m \u001b[0m│\n", - "└───────────────────┴───────┴────────────────┴──────────┴─────────────┴─────────┴─────────┴────────────┘\n" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/html": [ - "
\n",
-       "\n",
-       "
\n" - ], - "text/plain": [ - "\n", - "\n" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n", - "# 3. Mini-demo (only executed when you run the file directly)\n", - "# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n", - "# ── tiny “corpus” ─────────────────────────────────────── #\n", - "docs = [\n", - " Document(\n", - " id=\"A1\",\n", - " content=(\n", - " \"Symbolic AI combines formal logic with modern machine learning. \"\n", - " \"It allows transparent reasoning and explicit knowledge \"\n", - " \"representation while still benefiting from statistical models.\"\n", - " ),\n", - " ),\n", - " Document(\n", - " id=\"B2\",\n", - " content=(\n", - " \"Vector databases store embeddings of documents. They let users \"\n", - " \"quickly retrieve text that is semantically similar to a query \"\n", - " \"vector, enabling high-quality semantic search.\"\n", - " ),\n", - " ),\n", - " Document(\n", - " id=\"C3\",\n", - " content=(\n", - " \"Hybrid search merges sparse keyword techniques and dense vector \"\n", - " \"similarity, improving recall and precision, especially for \"\n", - " \"domain-specific collections.\"\n", - " ),\n", - " ),\n", - "]\n", - "\n", - "# ── create agent instance ─────────────────────────────── #\n", - "agent = MultiDocQAgent(min_coverage=0.6)\n", - "\n", - "# ── ask a question ────────────────────────────────────── #\n", - "question = \"Why are vector databases useful for semantic search?\"\n", - "result = agent(\n", - " input=MultiDocQAInput(\n", - " query=question,\n", - " documents=docs,\n", - " max_snippets=2, # caller sets stricter evidence limit\n", - " )\n", - ")\n", - "\n", - "# ── result ───────────────────────––––––––––––––––––––––– #\n", - "print(\"\\nAnswer:\\n\", result.answer)\n", - "print(\"\\nCoverage:\", result.coverage_score)\n", - "print(\"\\nEvidence:\")\n", - "for ev in result.evidence:\n", - " print(f\" • (Doc {ev.doc_id}) {ev.snippet}\")\n", - "\n", - "agent.contract_perf_stats();" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "65f28a95-1069-4581-8485-26d8215cdb7f", - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.12.9" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/symbolicai-main/symbolicai-main/examples/primitives.ipynb b/symbolicai-main/symbolicai-main/examples/primitives.ipynb deleted file mode 100644 index 3575b547dc09395dd16cf5935fa19c57331a0d3d..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/examples/primitives.ipynb +++ /dev/null @@ -1,2253 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Primitives Cheat-Sheet - SymbolicAI\n", - "\n", - "> _Primitives are the atoms of the SymbolicAI API – small, orthogonal operations that can be freely combined to express very rich behaviour. Every `Symbol` automatically inherits them, so there is no import-gymnastics required: just create a symbol and start hacking._\n", - "\n", - "This notebook gives you a **hands-on overview** of the most useful primitives that ship with `symai`. All examples are *runnable* – execute the cells and play with them!\n", - "\n", - "> ❗️**NOTE**❗️We will focus mostly on the **semantic** behaviour of the primitives, but you can also use them in **syntactic** mode, which is the default. Syntactic mode behaves like a normal Python value, unless otherwise specified." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Setup and Installation\n", - "\n", - "First, let's install and import the necessary dependencies:" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/Users/futurisold/miniconda3/envs/symai/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", - " from .autonotebook import tqdm as notebook_tqdm\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "SymbolicAI imported successfully!\n" - ] - } - ], - "source": [ - "# Install SymbolicAI if not already installed\n", - "# !pip install symbolicai\n", - "\n", - "# Import the main Symbol class\n", - "from symai import Symbol\n", - "\n", - "print(\"SymbolicAI imported successfully!\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 1. Syntactic vs. Semantic Symbols\n", - "\n", - "`Symbol` comes in **two flavours**:\n", - "\n", - "1. **Syntactic** – behaves like a normal Python value (string, list, int ‐ whatever you passed in).\n", - "2. **Semantic** – is wired to the neuro-symbolic engine and therefore *understands* meaning and context.\n", - "\n", - "### How to switch to the semantic view" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Semantic symbol: Cats are adorable\n" - ] - } - ], - "source": [ - "# 1. At creation time\n", - "s = Symbol(\"Cats are adorable\", semantic=True) # already semantic\n", - "print(f\"Semantic symbol: {s}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Syntactic startswith 'Cats': True\n", - "Semantic startswith 'animal': True\n", - "Semantic 'feline' in s: True\n", - "Split result: Cats\n" - ] - } - ], - "source": [ - "# 2. On demand with the .sem projection – the twin .syn flips you back\n", - "s = Symbol(\"Cats are adorable\") # default = syntactic\n", - "\n", - "print(f\"Syntactic startswith 'Cats': {s.startswith('Cats')}\")\n", - "print(f\"Semantic startswith 'animal': {s.sem.startswith('animal')}\")\n", - "print(f\"Semantic 'feline' in s: {'feline' in s.sem}\")\n", - "\n", - "# Syntactic operator split, syntactic index\n", - "result = (s / \" \")[0]\n", - "print(f\"Split result: {result}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 2. Inversion and Negation" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Original: I am standing on the shoulders of giants.\n", - "Inverted: The giants are standing on my shoulders.\n" - ] - } - ], - "source": [ - "# Inversion (~)\n", - "s = Symbol(\"I am standing on the shoulders of giants.\", semantic=True)\n", - "inverted = ~s\n", - "print(f\"Original: {s}\")\n", - "print(f\"Inverted: {inverted}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Original: I am happy.\n", - "Negated: I am not happy.\n" - ] - } - ], - "source": [ - "# Negation (-)\n", - "s = Symbol(\"I am happy.\", semantic=True)\n", - "negated = -s\n", - "print(f\"Original: {s}\")\n", - "print(f\"Negated: {negated}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 3. Comparison Operations\n", - "\n", - "### Equality (`==`) and Inequality (`!=`)\n", - "\n", - "The equality and inequality operators showcase one of the most powerful aspects of semantic symbols: **conceptual equivalence** rather than just literal matching." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "'Hello there!' == 'Hi there!': True\n", - "'Goodbye friend!' == 'See you later!': True\n" - ] - } - ], - "source": [ - "# Semantic greeting comparison - understands meaning\n", - "greeting_sem = Symbol('Hello there!', semantic=True)\n", - "greeting_variant = 'Hi there!'\n", - "\n", - "print(f\"'{greeting_sem}' == '{greeting_variant}': {greeting_sem == greeting_variant}\")\n", - "\n", - "# Semantic farewell comparison\n", - "farewell_sem = Symbol('Goodbye friend!', semantic=True)\n", - "farewell_variant = 'See you later!'\n", - "\n", - "print(f\"'{farewell_sem}' == '{farewell_variant}': {farewell_sem == farewell_variant}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 3] == [3, 2, 1] (semantic): False\n" - ] - } - ], - "source": [ - "# Works with lists too - semantic understanding\n", - "list_sem = Symbol([1, 2, 3], semantic=True)\n", - "list_different = Symbol([3, 2, 1], semantic=True)\n", - "\n", - "print(f\"[1, 2, 3] == [3, 2, 1] (semantic): {list_sem == list_different}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Contextual greeting comparison: True\n", - "Politeness level comparison: False\n" - ] - } - ], - "source": [ - "# Advanced Contextual Equality - Custom Context Comparison\n", - "greeting = Symbol('Hello, good morning!')\n", - "similar_greeting = 'Hi there, good day!'\n", - "\n", - "# Compare with specific greeting context\n", - "result = greeting.equals(similar_greeting, context='greeting context')\n", - "print(f\"Contextual greeting comparison: {result}\")\n", - "\n", - "# Compare with different contexts for nuanced evaluation\n", - "formal_greeting = Symbol('Good morning, sir.')\n", - "casual_greeting = 'Hey, what\\'s up?'\n", - "\n", - "# Context-aware politeness comparison\n", - "politeness_comparison = formal_greeting.equals(casual_greeting, context='politeness level')\n", - "print(f\"Politeness level comparison: {politeness_comparison}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 4. Membership Operations\n", - "\n", - "### The `in` Operator - Semantic Containment" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "'fruit' in 'apple banana cherry': True\n", - "'fruit' in ['apple', 'banana', 'cherry']: True\n" - ] - } - ], - "source": [ - "# Semantic string containment - understands concepts\n", - "str_sem = Symbol('apple banana cherry', semantic=True)\n", - "concept_search = 'fruit'\n", - "\n", - "print(f\"'{concept_search}' in '{str_sem}': {concept_search in str_sem}\")\n", - "\n", - "# Semantic list containment - conceptual understanding\n", - "list_sem = Symbol(['apple', 'banana', 'cherry'], semantic=True)\n", - "print(f\"'{concept_search}' in {list_sem.value}: {concept_search in list_sem}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "'pet' in 'cat dog bird fish': True\n", - "'mammal' in 'cat dog bird fish': True\n", - "'vehicle' in 'cat dog bird fish': False\n" - ] - } - ], - "source": [ - "# More examples of semantic containment\n", - "animals_sem = Symbol('cat dog bird fish', semantic=True)\n", - "print(f\"'pet' in '{animals_sem}': {'pet' in animals_sem}\")\n", - "print(f\"'mammal' in '{animals_sem}': {'mammal' in animals_sem}\")\n", - "print(f\"'vehicle' in '{animals_sem}': {'vehicle' in animals_sem}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "text.contains('car'): True\n", - "mixed_data.contains('two'): True\n", - "mixed_data.contains(True): True\n" - ] - } - ], - "source": [ - "# Enhanced Semantic Containment - Multi-Type Support\n", - "text = Symbol('The vehicle moved quickly down the road')\n", - "print(f\"text.contains('car'): {text.contains('car')}\")\n", - "\n", - "# Containment with mixed data types\n", - "mixed_data = Symbol([1, 'two', 3.0, True])\n", - "print(f\"mixed_data.contains('two'): {mixed_data.contains('two')}\")\n", - "print(f\"mixed_data.contains(True): {mixed_data.contains(True)}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 5. Ordering and Comparison Operations\n", - "\n", - "### Greater Than (`>`) and Less Than (`<`) and Greater or Equal (`>=`) and Less or Equal (`<=`)" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "'enormous' > 'tiny': True\n", - "'cat' < 'dog': True\n" - ] - } - ], - "source": [ - "# Semantic size comparison - understands relative magnitude\n", - "large_sem = Symbol('enormous', semantic=True)\n", - "small_sem = Symbol('tiny', semantic=True)\n", - "\n", - "print(f\"'{large_sem}' > '{small_sem}': {large_sem > small_sem}\")\n", - "\n", - "# Semantic animal size comparison\n", - "cat_sem = Symbol('cat', semantic=True)\n", - "dog_sem = Symbol('dog', semantic=True)\n", - "\n", - "print(f\"'{cat_sem}' < '{dog_sem}': {cat_sem < dog_sem}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "'freezing' < 'scorching': True\n", - "'fifty' > 45: True\n" - ] - } - ], - "source": [ - "# Temperature comparisons - semantic understanding of hot/cold\n", - "cold_sem = Symbol('freezing', semantic=True)\n", - "hot_sem = Symbol('scorching', semantic=True)\n", - "\n", - "print(f\"'{cold_sem}' < '{hot_sem}': {cold_sem < hot_sem}\")\n", - "\n", - "# Semantic number understanding\n", - "word_number = Symbol('fifty', semantic=True)\n", - "regular_number = 45\n", - "\n", - "print(f\"'{word_number}' > {regular_number}: {word_number > regular_number}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 6. Shift Operations - Semantic Inclusion\n", - "\n", - "### Left Shift (`<<`) and Right Shift (`>>`)" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "'data stream' << 'left': left data stream\n", - "'information flow' >> 'right': information right flow\n" - ] - } - ], - "source": [ - "# Left shift - prepend/include at the beginning\n", - "data_stream = Symbol('data stream', semantic=True)\n", - "left_direction = Symbol('left')\n", - "result = data_stream << left_direction\n", - "print(f\"'{data_stream}' << '{left_direction}': {result}\")\n", - "\n", - "# Right shift - append/include at the end\n", - "info_flow = Symbol('information flow', semantic=True)\n", - "right_direction = Symbol('right')\n", - "result = info_flow >> right_direction\n", - "print(f\"'{info_flow}' >> '{right_direction}': {result}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "'high priority task' << 'urgent': urgent high priority task\n", - "'data processing' >> 'downstream': downstream data processing\n" - ] - } - ], - "source": [ - "# Priority and urgency - prepend urgent to task\n", - "priority_task = Symbol('high priority task', semantic=True)\n", - "urgency = Symbol('urgent')\n", - "result = priority_task << urgency\n", - "print(f\"'{priority_task}' << '{urgency}': {result}\")\n", - "\n", - "# Process flow - append downstream to processing\n", - "data_process = Symbol('data processing', semantic=True)\n", - "downstream = Symbol('downstream')\n", - "result = data_process >> downstream\n", - "print(f\"'{data_process}' >> '{downstream}': {result}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 7. Bitwise and Logical Operations\n", - "\n", - "### Bitwise AND (`&`) - Intersection and Logical Conjunction" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Logical inference: Therefore, it is Sunday.\n", - "Combined evidence: Therefore, there is strong evidence linking the suspect to the scene.\n" - ] - } - ], - "source": [ - "# Semantic logical conjunction - combining facts and rules\n", - "horn_rule = Symbol('The horn only sounds on Sundays.', semantic=True)\n", - "observation = Symbol('I hear the horn.')\n", - "conclusion = horn_rule & observation\n", - "print(f\"Logical inference: {conclusion}\")\n", - "\n", - "# Combining evidence\n", - "evidence1 = Symbol('The suspect was seen at the scene.', semantic=True)\n", - "evidence2 = Symbol('His fingerprints were found.')\n", - "combined_evidence = evidence1 & evidence2\n", - "print(f\"Combined evidence: {combined_evidence}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Bitwise OR (`|`) - Union and Logical Disjunction" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Multiple possibilities: Either it might rain today, or it could be sunny, or both.\n", - "Alternative outcomes: The meeting could be postponed or canceled, perhaps both.\n" - ] - } - ], - "source": [ - "# Semantic logical disjunction - alternative possibilities\n", - "option1 = Symbol('It might rain today.', semantic=True)\n", - "option2 = Symbol('It could be sunny.')\n", - "possibilities = option1 | option2\n", - "print(f\"Multiple possibilities: {possibilities}\")\n", - "\n", - "# Alternative scenarios\n", - "scenario1 = Symbol('The meeting could be postponed.', semantic=True)\n", - "scenario2 = Symbol('The meeting might be canceled.')\n", - "alternatives = scenario1 | scenario2\n", - "print(f\"Alternative outcomes: {alternatives}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Bitwise XOR (`^`) - Exclusive OR" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Exclusive alternative: It will either rain today or be sunny, but not both.\n", - "Mutually exclusive states: Either the door is open or the door is closed, but not both.\n" - ] - } - ], - "source": [ - "# Semantic exclusive choice - either/or scenarios\n", - "exclusive1 = Symbol('Either it will rain today.', semantic=True)\n", - "exclusive2 = Symbol('Or it will be sunny.')\n", - "either_or = exclusive1 ^ exclusive2\n", - "print(f\"Exclusive alternative: {either_or}\")\n", - "\n", - "# Contradictory statements\n", - "statement1 = Symbol('The door is open.', semantic=True)\n", - "statement2 = Symbol('The door is closed.')\n", - "contradiction = statement1 ^ statement2\n", - "print(f\"Mutually exclusive states: {contradiction}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 8. Arithmetic Operations\n", - "\n", - "### Addition (`+`) and Subtraction (`-`)" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Text transformation: Hello my friend\n" - ] - } - ], - "source": [ - "enemy_text = Symbol('Hello my enemy', semantic=True)\n", - "result = enemy_text - 'enemy' + 'friend'\n", - "print(f\"Text transformation: {result}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### String Manipulation (`@`, `/`)" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Concatenated string: Hello my friend\n", - "Split string: ['Hello', 'my', 'friend']\n" - ] - } - ], - "source": [ - "# String concatenation with @\n", - "string = Symbol('Hello my ') @ 'friend'\n", - "print(f\"Concatenated string: {string}\")\n", - "\n", - "# String splitting with /\n", - "split_string = string / ' '\n", - "print(f\"Split string: {split_string}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 9. Indexing and Slicing Operations" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Name query result: Alice\n", - "Identity query result: {'name': 'Alice', 'age': '30', 'city': 'NYC'}\n" - ] - } - ], - "source": [ - "# Semantic dictionary access - finds conceptually related keys\n", - "sym_person = Symbol({'name': 'Alice', 'age': 30, 'city': 'NYC'}, semantic=True)\n", - "name_result = sym_person['Return any names']\n", - "print(f\"Name query result: {name_result}\")\n", - "\n", - "identity_result = sym_person['identity']\n", - "print(f\"Identity query result: {identity_result}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Domestic animal result: ['cat', 'dog', 'bird', 'fish']\n", - "Primary color result: ['#FF0000', '#00FF00', '#0000FF']\n" - ] - } - ], - "source": [ - "# Semantic list access - finds conceptually matching items\n", - "sym_animals = Symbol(['cat', 'dog', 'bird', 'fish'], semantic=True)\n", - "pet_result = sym_animals['domestic animal']\n", - "print(f\"Domestic animal result: {pet_result}\")\n", - "\n", - "# Color matching example\n", - "sym_colors = Symbol({'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}, semantic=True)\n", - "primary_color = sym_colors['primary color']\n", - "print(f\"Primary color result: {primary_color}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Modified weather data: {'temperature': 25, 'humidity': 60, 'pressure': 1013}\n" - ] - } - ], - "source": [ - "# Semantic dictionary modification - maps to conceptually similar keys\n", - "sym_weather = Symbol({'temperature': 20, 'humidity': 60, 'pressure': 1013}, semantic=True)\n", - "sym_weather['Change the temperature'] = 25\n", - "print(f\"Modified weather data: {sym_weather.value}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 10. Type Checking Operations\n", - "\n", - "### Semantic Type Validation (`isinstanceof`)" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Is 42 a number? True\n", - "Is 42 a string? False\n", - "Is list a list? False\n", - "Is True a logical value? True\n" - ] - } - ], - "source": [ - "# Basic semantic type checking\n", - "number_sym = Symbol(42)\n", - "print(f\"Is 42 a number? {number_sym.isinstanceof('number')}\")\n", - "print(f\"Is 42 a string? {number_sym.isinstanceof('string')}\")\n", - "\n", - "# Collection type checking\n", - "list_sym = Symbol(['apple', 'banana', 'cherry'])\n", - "print(f\"Is list a list? {list_sym.isinstanceof('list')}\")\n", - "\n", - "# Boolean/logical type checking\n", - "bool_sym = Symbol(True)\n", - "print(f\"Is True a logical value? {bool_sym.isinstanceof('logical value')}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Is dict person data? True\n", - "Is user_info a person? True\n" - ] - } - ], - "source": [ - "# Complex semantic type recognition\n", - "person_data = Symbol({'name': 'John', 'age': 30})\n", - "print(f\"Is dict person data? {person_data.isinstanceof('person data')}\")\n", - "\n", - "# More natural language type queries\n", - "user_info = Symbol({'name': 'Alice', 'age': 25, 'city': 'Wonderland'})\n", - "print(f\"Is user_info a person? {user_info.isinstanceof('person')}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 11. Basic Symbolic Manipulations\n", - "\n", - "### Expression Interpretation (`interpret`)" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Analogy result: Sun\n", - "Integration result: x³ + x² - 5x + C\n" - ] - } - ], - "source": [ - "# Symbolic reasoning and analogies\n", - "analogy = Symbol('gravity : Earth :: radiation : ?')\n", - "result = analogy.interpret()\n", - "print(f\"Analogy result: {result}\")\n", - "\n", - "# Mathematical expression interpretation\n", - "math_expr = Symbol(\"∫(3x² + 2x - 5)dx\")\n", - "solution = math_expr.interpret()\n", - "print(f\"Integration result: {solution}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "x = -5: 'negative'.\n", - "x = 0: x is 'negative' if x < 0, 'zero' if x = 0, and 'positive' if x > 0.\n", - "x = 10: positive\n" - ] - } - ], - "source": [ - "# Conditional interpretation with different inputs\n", - "conditional = Symbol(\"If x < 0 then 'negative' else if x == 0 then 'zero' else 'positive'\")\n", - "\n", - "# Test with different values\n", - "print(f\"x = -5: {conditional.interpret('x = -5')}\")\n", - "print(f\"x = 0: {conditional.interpret('x = 0')}\")\n", - "print(f\"x = 10: {conditional.interpret('x = 10')}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "System solution: x = 7, y = 3\n", - "Philosophical insight: What caused the universe's initial event?\n" - ] - } - ], - "source": [ - "# System solving and constraints\n", - "system = Symbol(\"Find values for x and y where: x + y = 10, x - y = 4\")\n", - "solution = system.interpret()\n", - "print(f\"System solution: {solution}\")\n", - "\n", - "# Logical reasoning with philosophical questions\n", - "reasoning = Symbol('If every event has a cause, and the universe began with an event, what philosophical question arises?')\n", - "philosophical_insight = reasoning.interpret()\n", - "print(f\"Philosophical insight: {philosophical_insight}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Step 1: E² = (pc)² + (mc²)²\n", - "Step 2: E ≈ pc\n", - "Step 3: E² = (pc)² + (m₀c²)²\n", - "All accumulated results: 3 steps\n" - ] - } - ], - "source": [ - "# Accumulative interpretation\n", - "sym_accumulate = Symbol('Relativistic electron formula')\n", - "result1 = sym_accumulate.interpret(accumulate=True)\n", - "print(f\"Step 1: {result1}\")\n", - "\n", - "result2 = result1.interpret('Assume the momentum to be extremely large', accumulate=True)\n", - "print(f\"Step 2: {result2}\")\n", - "\n", - "result3 = result2.interpret('Expand the formula to account for both mass and momentum', accumulate=True)\n", - "print(f\"Step 3: {result3}\")\n", - "\n", - "# Get all accumulated results\n", - "all_results = sym_accumulate.get_results()\n", - "print(f\"All accumulated results: {len(all_results)} steps\")\n", - "\n", - "# Clear results\n", - "sym_accumulate.clear_results()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 12. Data Processing and Manipulation Operations\n", - "\n", - "### Text Cleaning and Normalization (`clean`)" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Original: This text has multiple spaces and\n", - "\n", - "extra newlines.\t\tAnd tabs.\n", - "Cleaned: This text has multiple spaces and extra newlines. And tabs.\n" - ] - } - ], - "source": [ - "sym_dirty = Symbol(\"This text has multiple spaces and\\n\\nextra newlines.\\t\\tAnd tabs.\")\n", - "cleaned = sym_dirty.clean()\n", - "print(f\"Original: {sym_dirty.value}\")\n", - "print(f\"Cleaned: {cleaned}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Content Summarization (`summarize`)" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Original length: 322\n", - "Summarized:\n", - " Python is a high-level, interpreted programming language characterized by its dynamic semantics, built-in data structures, dynamic typing, and dynamic binding. These features make it highly suitable for Rapid Application Development and for use as a scripting or \"glue\" language to connect existing components.\n", - "Context-focused summary:\n", - " Python is an interpreted, high-level programming language known for its dynamic semantics. Its appeal for Rapid Application Development and its utility as a scripting or \"glue\" language stem from its high-level built-in data structures, dynamic typing, and dynamic binding.\n" - ] - } - ], - "source": [ - "sym_long = Symbol(\"Python is a high-level, interpreted programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.\")\n", - "summarized = sym_long.summarize()\n", - "print(f\"Original length: {len(sym_long.value)}\")\n", - "print(f\"Summarized:\\n {summarized}\")\n", - "\n", - "# With context for focused summarization\n", - "context_summarized = sym_long.summarize(context=\"Focus on Python's use in data science\")\n", - "print(f\"Context-focused summary:\\n {context_summarized}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Content Outlining (`outline`)" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Outline:\n", - " ['- Machine learning: subset of AI enabling computers to learn and improve from experience without explicit programming', '- Supervised learning: uses labeled training data to learn mapping function', '- Classification: predicts discrete class labels', '- Regression: predicts continuous numerical values', '- Unsupervised learning: finds hidden patterns in data without labeled examples']\n" - ] - } - ], - "source": [ - "sym_complex = Symbol(\"\"\"\n", - "# Introduction to Machine Learning\n", - "Machine learning is a subset of artificial intelligence that enables computers to learn and improve from experience without being explicitly programmed.\n", - "\n", - "## Supervised Learning\n", - "Supervised learning uses labeled training data to learn a mapping function.\n", - "\n", - "### Classification\n", - "Classification predicts discrete class labels.\n", - "\n", - "### Regression\n", - "Regression predicts continuous numerical values.\n", - "\n", - "## Unsupervised Learning\n", - "Unsupervised learning finds hidden patterns in data without labeled examples.\n", - "\"\"\")\n", - "\n", - "outlined = sym_complex.outline()\n", - "print(f\"Outline:\\n {outlined}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Content Filtering (`filter`)" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Exclude cats: Dogs are loyal pets. Hamsters are small pets.\n", - "Include only dogs: Dogs are loyal pets.\n" - ] - } - ], - "source": [ - "sym_mixed = Symbol(\"Dogs are loyal pets. Cats are independent pets. Hamsters are small pets.\")\n", - "\n", - "# Exclude content matching criteria (default behavior)\n", - "filtered_ex = sym_mixed.filter(criteria=\"Cats\")\n", - "print(f\"Exclude cats: {filtered_ex}\")\n", - "\n", - "# Include only content matching criteria\n", - "filtered_in = sym_mixed.filter(criteria=\"Dogs\", include=True)\n", - "print(f\"Include only dogs: {filtered_in}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Content Modification (`modify`)" - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Original: The quick brown fox jumps over the lazy dog.\n", - "Modified: The fast brown fox jumps over the sleeping dog.\n" - ] - } - ], - "source": [ - "sym_original = Symbol(\"The quick brown fox jumps over the lazy dog.\")\n", - "changes = \"Change 'quick' to 'fast' and 'lazy' to 'sleeping'\"\n", - "modified = sym_original.modify(changes=changes)\n", - "print(f\"Original: {sym_original}\")\n", - "print(f\"Modified: {modified}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Text Replacement (`replace`)" - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Original: Python is a programming language. Python is easy to learn.\n", - "Replaced: JavaScript is a programming language. JavaScript is easy to learn.\n" - ] - } - ], - "source": [ - "sym_replace = Symbol(\"Python is a programming language. Python is easy to learn.\")\n", - "replaced = sym_replace.replace(\"Python\", \"JavaScript\")\n", - "print(f\"Original: {sym_replace}\")\n", - "print(f\"Replaced: {replaced}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Content Removal (`remove`)" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Original: This text contains [unnecessary information] that should be removed.\n", - "Removed: This text contains that should be removed.\n" - ] - } - ], - "source": [ - "sym_extra = Symbol(\"This text contains [unnecessary information] that should be removed.\")\n", - "removed = sym_extra.remove(\"[unnecessary information] \")\n", - "print(f\"Original: {sym_extra}\")\n", - "print(f\"Removed: {removed}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Content Addition (`include`, `combine`)" - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Included: This is the main content. This is additional information.\n", - "Combined: This is the main content. Second part of the content.\n" - ] - } - ], - "source": [ - "sym_base = Symbol(\"This is the main content.\")\n", - "\n", - "# Include additional information\n", - "included = sym_base.include(\"This is additional information.\")\n", - "print(f\"Included: {included}\")\n", - "\n", - "# Combine with other content\n", - "combined = sym_base.combine(\"Second part of the content.\")\n", - "print(f\"Combined: {combined}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Semantic Mapping (`map`)" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Vowel transformation: h2ll4 w4rld\n", - "Case transformation: prOgrAmmIng\n" - ] - } - ], - "source": [ - "# Transform characters in strings\n", - "text = Symbol(\"hello world\")\n", - "result = text.map('convert vowels to numbers: a=1, e=2, i=3, o=4, u=5')\n", - "print(f\"Vowel transformation: {result}\")\n", - "\n", - "# Transform case selectively\n", - "caps_text = Symbol(\"PROGRAMMING\")\n", - "result = caps_text.map('make consonants lowercase, keep vowels uppercase')\n", - "print(f\"Case transformation: {result}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Fruit to vegetable transformation: ['carrot', 'broccoli', 'spinach', 'cat', 'dog']\n", - "Dictionary transformation: `{'item1': 'carrot', 'item2': 'broccoli', 'item3': 'cat'}`\n" - ] - } - ], - "source": [ - "# Transform fruits to vegetables, leave animals unchanged\n", - "mixed_list = Symbol(['apple', 'banana', 'cherry', 'cat', 'dog'])\n", - "result = mixed_list.map('convert all fruits to vegetables')\n", - "print(f\"Fruit to vegetable transformation: {result}\")\n", - "\n", - "# Work with dictionaries - transforms values, preserves keys\n", - "fruit_dict = Symbol({'item1': 'apple', 'item2': 'banana', 'item3': 'cat'})\n", - "result = fruit_dict.map('convert fruits to vegetables')\n", - "print(f\"Dictionary transformation: {result}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Emotions to weather: ['sunny', 'rainy', 'stormy']\n", - "Type preserved: \n" - ] - } - ], - "source": [ - "# Preserve container types\n", - "emotions_tuple = Symbol(('happy', 'sad', 'angry'))\n", - "weather = emotions_tuple.map('convert emotions to weather')\n", - "print(f\"Emotions to weather: {weather}\")\n", - "print(f\"Type preserved: {type(weather)}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 13. Pattern Matching and Intelligence Operations\n", - "\n", - "### Content Ranking (`rank`)" - ] - }, - { - "cell_type": "code", - "execution_count": 41, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Ranked by difficulty:\n", - " 3. Practice coding\n", - "5. Learn Python basics\n", - "2. Set up IDE\n", - "1. Install Python\n", - "4. Join community\n" - ] - } - ], - "source": [ - "sym_numbers = Symbol(\"\"\"\n", - "5. Learn Python basics\n", - "1. Install Python\n", - "3. Practice coding\n", - "2. Set up IDE\n", - "4. Join community\n", - "\"\"\")\n", - "ranked = sym_numbers.rank(measure='difficulty', order='desc')\n", - "print(f\"Ranked by difficulty:\\n {ranked}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 42, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Ranked by priority: ['Optional task: Update documentation', 'Important task: Complete project proposal', 'Urgent task: Fix critical bug', 'Critical task: Deploy hotfix']\n" - ] - } - ], - "source": [ - "# Ranking by priority\n", - "sym_tasks = Symbol(\"\"\"\n", - "Important task: Complete project proposal\n", - "Urgent task: Fix critical bug\n", - "Optional task: Update documentation\n", - "Critical task: Deploy hotfix\n", - "\"\"\")\n", - "ranked_priority = sym_tasks.rank(measure='priority', order='asc')\n", - "print(f\"Ranked by priority: {ranked_priority}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Pattern Extraction (`extract`)" - ] - }, - { - "cell_type": "code", - "execution_count": 43, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Extracted contact details: Email: john.doe@email.com | Phone: +1-555-0123 | Address: 123 Main St, City\n", - "Extracted dates: 2024-03-15\n" - ] - } - ], - "source": [ - "sym_contact = Symbol(\"\"\"\n", - "Contact Information:\n", - "Email: john.doe@email.com\n", - "Phone: +1-555-0123\n", - "Address: 123 Main St, City\n", - "\"\"\")\n", - "extracted = sym_contact.extract(\"contact details\")\n", - "print(f\"Extracted contact details: {extracted}\")\n", - "\n", - "# Extract specific patterns like dates\n", - "sym_text = Symbol(\"\"\"\n", - "Project deadline: 2024-03-15\n", - "Budget allocated: $50,000\n", - "Team size: 8 people\n", - "Status: In Progress\n", - "\"\"\")\n", - "extracted_dates = sym_text.extract(\"dates and deadlines\")\n", - "print(f\"Extracted dates: {extracted_dates}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Code Correction (`correct`)" - ] - }, - { - "cell_type": "code", - "execution_count": 44, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Original code:\n", - " def calculate_sum(a b):\n", - " return a + b\n", - "\n", - "Corrected code:\n", - " def calculate_sum(a, b):\n", - " return a + b\n" - ] - } - ], - "source": [ - "# Fix syntax errors\n", - "sym_code = Symbol(\"\"\"def calculate_sum(a b):\n", - " return a + b\n", - "\"\"\")\n", - "corrected = sym_code.correct(\"Fix the code\", exception=SyntaxError)\n", - "print(f\"Original code:\\n {sym_code.value}\")\n", - "print(f\"Corrected code:\\n {corrected}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 45, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Original code:\n", - " \n", - "def process_data(items):\n", - " return items.sort()\n", - "result = process_data([3, 1, 2])\n", - "print(result + 1) # TypeError: NoneType + int\n", - "\n", - "Corrected code:\n", - " def process_data(items):\n", - " return sorted(items)\n", - "result = process_data([3, 1, 2])\n", - "print(result[0] + 1)\n" - ] - } - ], - "source": [ - "# Fix type errors\n", - "sym_type_error = Symbol(\"\"\"\n", - "def process_data(items):\n", - " return items.sort()\n", - "result = process_data([3, 1, 2])\n", - "print(result + 1) # TypeError: NoneType + int\n", - "\"\"\")\n", - "corrected_type = sym_type_error.correct(\"Fix the code\", exception=TypeError)\n", - "print(f\"Original code:\\n {sym_type_error.value}\")\n", - "print(f\"Corrected code:\\n {corrected_type}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Language Translation (`translate`)" - ] - }, - { - "cell_type": "code", - "execution_count": 46, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "English: Hello, how are you today?\n", - "Spanish: Hola, ¿cómo estás hoy?\n", - "Informal English: Hey there! What's up?\n", - "Formal French: Salut ! Quoi de neuf ?\n" - ] - } - ], - "source": [ - "sym_english = Symbol(\"Hello, how are you today?\")\n", - "translated = sym_english.translate(\"Spanish\")\n", - "print(f\"English: {sym_english}\")\n", - "print(f\"Spanish: {translated}\")\n", - "\n", - "# Formal translation\n", - "sym_informal = Symbol(\"Hey there! What's up?\")\n", - "translated_formal = sym_informal.translate(\"French\", formal=True)\n", - "print(f\"Informal English: {sym_informal}\")\n", - "print(f\"Formal French: {translated_formal}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Multi-Choice Classification (`choice`)" - ] - }, - { - "cell_type": "code", - "execution_count": 47, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Weather classification: hot and humid\n", - "Sentiment classification: positive\n" - ] - } - ], - "source": [ - "sym_weather = Symbol(\"Temperature: 85°F, Humidity: 70%, Conditions: Sunny\")\n", - "cases = [\"hot and humid\", \"mild\", \"cold and dry\"]\n", - "weather_choice = sym_weather.choice(cases=cases, default=\"mild\")\n", - "print(f\"Weather classification: {weather_choice}\")\n", - "\n", - "# Sentiment analysis\n", - "sym_sentiment = Symbol(\"This product exceeded all my expectations! Absolutely wonderful!\")\n", - "sentiment_cases = [\"positive\", \"neutral\", \"negative\"]\n", - "sentiment_choice = sym_sentiment.choice(cases=sentiment_cases, default=\"neutral\")\n", - "print(f\"Sentiment classification: {sentiment_choice}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Format Conversion (`convert`)" - ] - }, - { - "cell_type": "code", - "execution_count": 48, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "YAML conversion:\n", - " name: John\n", - "age: 30\n", - "city: New York\n", - "XML conversion:\n", - " \n", - " John\n", - " 30\n", - " New York\n", - "\n" - ] - } - ], - "source": [ - "sym_json = Symbol('{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}')\n", - "\n", - "yaml_converted = sym_json.convert(\"YAML\")\n", - "print(f\"YAML conversion:\\n {yaml_converted}\")\n", - "\n", - "xml_converted = sym_json.convert(\"XML\")\n", - "print(f\"XML conversion:\\n {xml_converted}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 49, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "HTML table conversion:\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
NameAgeDepartment
Alice28Engineering
Bob35Marketing
\n" - ] - } - ], - "source": [ - "# Convert CSV to HTML table\n", - "sym_csv = Symbol(\"Name,Age,Department\\nAlice,28,Engineering\\nBob,35,Marketing\")\n", - "table_converted = sym_csv.convert(\"HTML table\")\n", - "print(f\"HTML table conversion:\\n {table_converted}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Content Transcription (`transcribe`)" - ] - }, - { - "cell_type": "code", - "execution_count": 50, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Informal: Hey there! How's it going? Hope you're doing well!\n", - "Formal: Hello. I hope this message finds you well.\n", - "Technical: The system crashed because of insufficient memory allocation.\n", - "Simple: The computer stopped working because it didn't have enough space to remember everything it needed to do.\n" - ] - } - ], - "source": [ - "sym_informal = Symbol(\"Hey there! How's it going? Hope you're doing well!\")\n", - "formal_transcribed = sym_informal.transcribe(\"make it formal and professional\")\n", - "print(f\"Informal: {sym_informal}\")\n", - "print(f\"Formal: {formal_transcribed}\")\n", - "\n", - "sym_technical = Symbol(\"The system crashed because of insufficient memory allocation.\")\n", - "simple_transcribed = sym_technical.transcribe(\"explain in simple terms for non-technical audience\")\n", - "print(f\"Technical: {sym_technical}\")\n", - "print(f\"Simple: {simple_transcribed}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 14. Execution Control and Code Operations\n", - "\n", - "### Code Analysis (`analyze`)" - ] - }, - { - "cell_type": "code", - "execution_count": 51, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Analysis result: Ensure that the input value provided to a function or operation is valid and meets the expected criteria.\n" - ] - } - ], - "source": [ - "sym_code = Symbol(\"print('Hello World')\")\n", - "try:\n", - " raise ValueError(\"Sample error for testing\")\n", - "except Exception as e:\n", - " analyzed = sym_code.analyze(exception=e, query=\"What went wrong?\")\n", - " print(f\"Analysis result: {analyzed}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Code Execution (`execute`, `fexecute`)" - ] - }, - { - "cell_type": "code", - "execution_count": 52, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Execution result:\n", - " {'globals': '{\\'__builtins__\\': {\\'__name__\\': \\'builtins\\', \\'__doc__\\': \"Built-in functions, types, exceptions, and other objects.\\\\n\\\\nThis module provides direct access to all \\'built-in\\'\\\\nidentifiers of Python; for example, builtins.len is\\\\nthe full name for the built-in function len().\\\\n\\\\nThis module is not normally accessed explicitly by most\\\\napplications, but can be useful in modules that provide\\\\nobjects with the same name as a built-in value, but in\\\\nwhich the built-in of that name is also needed.\", \\'__package__\\': \\'\\', \\'__loader__\\': , \\'__spec__\\': ModuleSpec(name=\\'builtins\\', loader=, origin=\\'built-in\\'), \\'__build_class__\\': , \\'__import__\\': , \\'abs\\': , \\'all\\': , \\'any\\': , \\'ascii\\': , \\'bin\\': , \\'breakpoint\\': , \\'callable\\': , \\'chr\\': , \\'compile\\': , \\'delattr\\': , \\'dir\\': , \\'divmod\\': , \\'eval\\': , \\'exec\\': , \\'format\\': , \\'getattr\\': , \\'globals\\': , \\'hasattr\\': , \\'hash\\': , \\'hex\\': , \\'id\\': , \\'input\\': >, \\'isinstance\\': , \\'issubclass\\': , \\'iter\\': , \\'aiter\\': , \\'len\\': , \\'locals\\': , \\'max\\': , \\'min\\': , \\'next\\': , \\'anext\\': , \\'oct\\': , \\'ord\\': , \\'pow\\': , \\'print\\': , \\'repr\\': , \\'round\\': , \\'setattr\\': , \\'sorted\\': , \\'sum\\': , \\'vars\\': , \\'None\\': None, \\'Ellipsis\\': Ellipsis, \\'NotImplemented\\': NotImplemented, \\'False\\': False, \\'True\\': True, \\'bool\\': , \\'memoryview\\': , \\'bytearray\\': , \\'bytes\\': , \\'classmethod\\': , \\'complex\\': , \\'dict\\': , \\'enumerate\\': , \\'filter\\': , \\'float\\': , \\'frozenset\\': , \\'property\\': , \\'int\\': , \\'list\\': , \\'map\\': , \\'object\\': , \\'range\\': , \\'reversed\\': , \\'set\\': , \\'slice\\': , \\'staticmethod\\': , \\'str\\': , \\'super\\': , \\'tuple\\': , \\'type\\': , \\'zip\\': , \\'__debug__\\': True, \\'BaseException\\': , \\'BaseExceptionGroup\\': , \\'Exception\\': , \\'GeneratorExit\\': , \\'KeyboardInterrupt\\': , \\'SystemExit\\': , \\'ArithmeticError\\': , \\'AssertionError\\': , \\'AttributeError\\': , \\'BufferError\\': , \\'EOFError\\': , \\'ImportError\\': , \\'LookupError\\': , \\'MemoryError\\': , \\'NameError\\': , \\'OSError\\': , \\'ReferenceError\\': , \\'RuntimeError\\': , \\'StopAsyncIteration\\': , \\'StopIteration\\': , \\'SyntaxError\\': , \\'SystemError\\': , \\'TypeError\\': , \\'ValueError\\': , \\'Warning\\': , \\'FloatingPointError\\': , \\'OverflowError\\': , \\'ZeroDivisionError\\': , \\'BytesWarning\\': , \\'DeprecationWarning\\': , \\'EncodingWarning\\': , \\'FutureWarning\\': , \\'ImportWarning\\': , \\'PendingDeprecationWarning\\': , \\'ResourceWarning\\': , \\'RuntimeWarning\\': , \\'SyntaxWarning\\': , \\'UnicodeWarning\\': , \\'UserWarning\\': , \\'BlockingIOError\\': , \\'ChildProcessError\\': , \\'ConnectionError\\': , \\'FileExistsError\\': , \\'FileNotFoundError\\': , \\'InterruptedError\\': , \\'IsADirectoryError\\': , \\'NotADirectoryError\\': , \\'PermissionError\\': , \\'ProcessLookupError\\': , \\'TimeoutError\\': , \\'IndentationError\\': , \\'IndexError\\': , \\'KeyError\\': , \\'ModuleNotFoundError\\': , \\'NotImplementedError\\': , \\'RecursionError\\': , \\'UnboundLocalError\\': , \\'UnicodeError\\': , \\'BrokenPipeError\\': , \\'ConnectionAbortedError\\': , \\'ConnectionRefusedError\\': , \\'ConnectionResetError\\': , \\'TabError\\': , \\'UnicodeDecodeError\\': , \\'UnicodeEncodeError\\': , \\'UnicodeTranslateError\\': , \\'ExceptionGroup\\': , \\'EnvironmentError\\': , \\'IOError\\': , \\'open\\': , \\'copyright\\': Copyright (c) 2001-2023 Python Software Foundation.\\nAll Rights Reserved.\\n\\nCopyright (c) 2000 BeOpen.com.\\nAll Rights Reserved.\\n\\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\\nAll Rights Reserved.\\n\\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\\nAll Rights Reserved., \\'credits\\': Thanks to CWI, CNRI, BeOpen, Zope Corporation, the Python Software\\n Foundation, and a cast of thousands for supporting Python\\n development. See www.python.org for more information., \\'license\\': Type license() to see the full license text, \\'help\\': Type help() for interactive help, or help(object) for help about object., \\'execfile\\': , \\'runfile\\': , \\'__IPYTHON__\\': True, \\'display\\': , \\'get_ipython\\': >}}', 'locals': \"{'run': , 'res': 5}\", 'locals_res': '5'}\n", - "Fallback execution result:\n", - " {'globals': '{\\'__builtins__\\': {\\'__name__\\': \\'builtins\\', \\'__doc__\\': \"Built-in functions, types, exceptions, and other objects.\\\\n\\\\nThis module provides direct access to all \\'built-in\\'\\\\nidentifiers of Python; for example, builtins.len is\\\\nthe full name for the built-in function len().\\\\n\\\\nThis module is not normally accessed explicitly by most\\\\napplications, but can be useful in modules that provide\\\\nobjects with the same name as a built-in value, but in\\\\nwhich the built-in of that name is also needed.\", \\'__package__\\': \\'\\', \\'__loader__\\': , \\'__spec__\\': ModuleSpec(name=\\'builtins\\', loader=, origin=\\'built-in\\'), \\'__build_class__\\': , \\'__import__\\': , \\'abs\\': , \\'all\\': , \\'any\\': , \\'ascii\\': , \\'bin\\': , \\'breakpoint\\': , \\'callable\\': , \\'chr\\': , \\'compile\\': , \\'delattr\\': , \\'dir\\': , \\'divmod\\': , \\'eval\\': , \\'exec\\': , \\'format\\': , \\'getattr\\': , \\'globals\\': , \\'hasattr\\': , \\'hash\\': , \\'hex\\': , \\'id\\': , \\'input\\': >, \\'isinstance\\': , \\'issubclass\\': , \\'iter\\': , \\'aiter\\': , \\'len\\': , \\'locals\\': , \\'max\\': , \\'min\\': , \\'next\\': , \\'anext\\': , \\'oct\\': , \\'ord\\': , \\'pow\\': , \\'print\\': , \\'repr\\': , \\'round\\': , \\'setattr\\': , \\'sorted\\': , \\'sum\\': , \\'vars\\': , \\'None\\': None, \\'Ellipsis\\': Ellipsis, \\'NotImplemented\\': NotImplemented, \\'False\\': False, \\'True\\': True, \\'bool\\': , \\'memoryview\\': , \\'bytearray\\': , \\'bytes\\': , \\'classmethod\\': , \\'complex\\': , \\'dict\\': , \\'enumerate\\': , \\'filter\\': , \\'float\\': , \\'frozenset\\': , \\'property\\': , \\'int\\': , \\'list\\': , \\'map\\': , \\'object\\': , \\'range\\': , \\'reversed\\': , \\'set\\': , \\'slice\\': , \\'staticmethod\\': , \\'str\\': , \\'super\\': , \\'tuple\\': , \\'type\\': , \\'zip\\': , \\'__debug__\\': True, \\'BaseException\\': , \\'BaseExceptionGroup\\': , \\'Exception\\': , \\'GeneratorExit\\': , \\'KeyboardInterrupt\\': , \\'SystemExit\\': , \\'ArithmeticError\\': , \\'AssertionError\\': , \\'AttributeError\\': , \\'BufferError\\': , \\'EOFError\\': , \\'ImportError\\': , \\'LookupError\\': , \\'MemoryError\\': , \\'NameError\\': , \\'OSError\\': , \\'ReferenceError\\': , \\'RuntimeError\\': , \\'StopAsyncIteration\\': , \\'StopIteration\\': , \\'SyntaxError\\': , \\'SystemError\\': , \\'TypeError\\': , \\'ValueError\\': , \\'Warning\\': , \\'FloatingPointError\\': , \\'OverflowError\\': , \\'ZeroDivisionError\\': , \\'BytesWarning\\': , \\'DeprecationWarning\\': , \\'EncodingWarning\\': , \\'FutureWarning\\': , \\'ImportWarning\\': , \\'PendingDeprecationWarning\\': , \\'ResourceWarning\\': , \\'RuntimeWarning\\': , \\'SyntaxWarning\\': , \\'UnicodeWarning\\': , \\'UserWarning\\': , \\'BlockingIOError\\': , \\'ChildProcessError\\': , \\'ConnectionError\\': , \\'FileExistsError\\': , \\'FileNotFoundError\\': , \\'InterruptedError\\': , \\'IsADirectoryError\\': , \\'NotADirectoryError\\': , \\'PermissionError\\': , \\'ProcessLookupError\\': , \\'TimeoutError\\': , \\'IndentationError\\': , \\'IndexError\\': , \\'KeyError\\': , \\'ModuleNotFoundError\\': , \\'NotImplementedError\\': , \\'RecursionError\\': , \\'UnboundLocalError\\': , \\'UnicodeError\\': , \\'BrokenPipeError\\': , \\'ConnectionAbortedError\\': , \\'ConnectionRefusedError\\': , \\'ConnectionResetError\\': , \\'TabError\\': , \\'UnicodeDecodeError\\': , \\'UnicodeEncodeError\\': , \\'UnicodeTranslateError\\': , \\'ExceptionGroup\\': , \\'EnvironmentError\\': , \\'IOError\\': , \\'open\\': , \\'copyright\\': Copyright (c) 2001-2023 Python Software Foundation.\\nAll Rights Reserved.\\n\\nCopyright (c) 2000 BeOpen.com.\\nAll Rights Reserved.\\n\\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\\nAll Rights Reserved.\\n\\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\\nAll Rights Reserved., \\'credits\\': Thanks to CWI, CNRI, BeOpen, Zope Corporation, the Python Software\\n Foundation, and a cast of thousands for supporting Python\\n development. See www.python.org for more information., \\'license\\': Type license() to see the full license text, \\'help\\': Type help() for interactive help, or help(object) for help about object., \\'execfile\\': , \\'runfile\\': , \\'__IPYTHON__\\': True, \\'display\\': , \\'get_ipython\\': >}}', 'locals': \"{'run': , 'res': 5}\", 'locals_res': '5'}\n" - ] - } - ], - "source": [ - "sym_code = Symbol(\"\"\"\n", - "def run():\n", - " return 2 + 3\n", - "res = run()\n", - "\"\"\")\n", - "executed = sym_code.execute()\n", - "print(f\"Execution result:\\n {executed}\")\n", - "\n", - "# Fallback execution\n", - "fexecuted = sym_code.fexecute()\n", - "print(f\"Fallback execution result:\\n {fexecuted}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Code Simulation (`simulate`)" - ] - }, - { - "cell_type": "code", - "execution_count": 53, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Algorithm simulation:\n", - " Step 4: Assign the result (15) to the variable 'result'\n", - "Fibonacci simulation:\n", - " PSEUDOCODE SIMULATION:\n", - "FUNCTION fibonacci(n):\n", - " IF n <= 1 THEN RETURN n\n", - " ELSE RETURN fibonacci(n-1) + fibonacci(n-2)\n", - "END FUNCTION\n", - "\n", - "EXECUTION TRACE (assuming an example call `fibonacci(5)`):\n", - "Call fibonacci(5)\n", - " n = 5, not <= 1. Returns fibonacci(4) + fibonacci(3)\n", - " Call fibonacci(4)\n", - " n = 4, not <= 1. Returns fibonacci(3) + fibonacci(2)\n", - " Call fibonacci(3)\n", - " n = 3, not <= 1. Returns fibonacci(2) + fibonacci(1)\n", - " Call fibonacci(2)\n", - " n = 2, not <= 1. Returns fibonacci(1) + fibonacci(0)\n", - " Call fibonacci(1)\n", - " n = 1, <= 1. Returns 1\n", - " Call fibonacci(0)\n", - " n = 0, <= 1. Returns 0\n", - " Unwinding fibonacci(2): 1 + 0 = 1\n", - " Call fibonacci(1)\n", - " n = 1, <= 1. Returns 1\n", - " Unwinding fibonacci(3): 1 + 1 = 2\n", - " Call fibonacci(2)\n", - " n = 2, not <= 1. Returns fibonacci(1) + fibonacci(0)\n", - " Call fibonacci(1)\n", - " n = 1, <= 1. Returns 1\n", - " Call fibonacci(0)\n", - " n = 0, <= 1. Returns 0\n", - " Unwinding fibonacci(2): 1 + 0 = 1\n", - " Unwinding fibonacci(4): 2 + 1 = 3\n", - " Call fibonacci(3)\n", - " n = 3, not <= 1. Returns fibonacci(2) + fibonacci(1)\n", - " Call fibonacci(2)\n", - " n = 2, not <= 1. Returns fibonacci(1) + fibonacci(0)\n", - " Call fibonacci(1)\n", - " n = 1, <= 1. Returns 1\n", - " Call fibonacci(0)\n", - " n = 0, <= 1. Returns 0\n", - " Unwinding fibonacci(2): 1 + 0 = 1\n", - " Call fibonacci(1)\n", - " n = 1, <= 1. Returns 1\n", - " Unwinding fibonacci(3): 1 + 1 = 2\n", - " Unwinding fibonacci(5): 3 + 2 = 5\n", - "Result (for fibonacci(5)): 5\n" - ] - } - ], - "source": [ - "sym_algorithm = Symbol(\"x = 5; y = 10; result = x + y\")\n", - "simulated = sym_algorithm.simulate()\n", - "print(f\"Algorithm simulation:\\n {simulated}\")\n", - "\n", - "# Complex algorithm simulation\n", - "sym_fibonacci = Symbol(\"def fibonacci(n): return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)\")\n", - "algorithm_sim = sym_fibonacci.simulate()\n", - "print(f\"Fibonacci simulation:\\n {algorithm_sim}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Information Sufficiency (`sufficient`)" - ] - }, - { - "cell_type": "code", - "execution_count": 54, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Information sufficiency: False\n" - ] - } - ], - "source": [ - "sym_info = Symbol(\"Product Name: UltraBook Pro\\nPrice: $1299\\nRAM: 16GB\")\n", - "sufficient_check = sym_info.sufficient(\"Is this enough information to make a purchase decision?\")\n", - "print(f\"Information sufficiency: {sufficient_check}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### List Processing (`list`, `foreach`)" - ] - }, - { - "cell_type": "code", - "execution_count": 55, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Engineers list: ['David']\n", - "Squared numbers: '['1', '4', '9', '16', '25']\n" - ] - } - ], - "source": [ - "sym_employees = Symbol(\"\"\"\n", - "Bob - Manager - $85000\n", - "Carol - Designer - $65000\n", - "David - Engineer - $72000\n", - "\"\"\")\n", - "\n", - "engineers_list = sym_employees.list(\"employees who are engineers\")\n", - "print(f\"Engineers list: {engineers_list}\")\n", - "\n", - "# Apply operations to each item\n", - "sym_numbers = Symbol([1, 2, 3, 4, 5])\n", - "squared_numbers = sym_numbers.foreach(\"each number\", \"square the number\")\n", - "print(f\"Squared numbers: {squared_numbers}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 15. Dictionary Handling Operations\n", - "\n", - "### Dictionary Creation (`dict`)" - ] - }, - { - "cell_type": "code", - "execution_count": 56, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Fruit categorization: {'fruits': \"['apples', 'oranges', 'bananas']\", 'description': \"['I have', 'in my kitchen.']\"}\n", - "Food organization: {'dairy': \"['milk', 'cheese']\", 'grains': \"['bread', 'rice']\", 'fruits and vegetables': \"['apples', 'broccoli']\", 'proteins': \"['eggs', 'chicken']\"}\n" - ] - } - ], - "source": [ - "sym_text = Symbol(\"I have apples, oranges, and bananas in my kitchen.\")\n", - "dict_result = sym_text.dict(\"categorize fruits\")\n", - "print(f\"Fruit categorization: {dict_result}\")\n", - "\n", - "sym_shopping = Symbol(\"milk, bread, eggs, apples, cheese, chicken, broccoli, rice\")\n", - "food_dict = sym_shopping.dict(\"organize by food categories\")\n", - "print(f\"Food organization: {food_dict}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 16. Template and Styling Operations\n", - "\n", - "### Template Substitution (`template`)" - ] - }, - { - "cell_type": "code", - "execution_count": 57, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Template result: Hello Alice, welcome to our service!\n", - "Custom template result: Product: Premium Headphones - Now available!\n" - ] - } - ], - "source": [ - "sym_name = Symbol(\"Alice\")\n", - "template_str = \"Hello {{placeholder}}, welcome to our service!\"\n", - "templated_result = sym_name.template(template_str)\n", - "print(f\"Template result: {templated_result}\")\n", - "\n", - "# Custom placeholder\n", - "sym_product = Symbol(\"Premium Headphones\")\n", - "custom_template = \"Product: ***ITEM*** - Now available!\"\n", - "custom_templated = sym_product.template(custom_template, placeholder=\"***ITEM***\")\n", - "print(f\"Custom template result: {custom_templated}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Content Styling (`style`)" - ] - }, - { - "cell_type": "code", - "execution_count": 58, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Styled text:\n", - " This is basic text that needs styling.\n", - "Styled code:\n", - " ```python\n", - "print('Hello World')\n", - "```\n" - ] - } - ], - "source": [ - "sym_content = Symbol(\"This is basic text that needs styling.\")\n", - "styled_result = sym_content.style(\"Make this text bold and italic\")\n", - "print(f\"Styled text:\\n {styled_result}\")\n", - "\n", - "sym_code = Symbol(\"print('Hello World')\")\n", - "styled_code = sym_code.style(\"Format as Python code with syntax highlighting\", libraries=[\"python\"])\n", - "print(f\"Styled code:\\n {styled_code}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 17. Data Clustering Operations\n", - "\n", - "### Semantic Clustering (`cluster`)" - ] - }, - { - "cell_type": "code", - "execution_count": 59, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Fruit clustering: {np.int64(-1): \"['banana']\", np.int64(0): \"['apple', 'orange']\", np.int64(1): \"['cherry', 'grape']\"}\n", - "Sentence clustering: {np.int64(-1): '[\\'The weather is sunny today.\\', \"It\\'s raining heavily outside.\", \\'Beautiful sunny weather today.\\']'}\n" - ] - } - ], - "source": [ - "sym_fruits = Symbol([\"apple\", \"banana\", \"cherry\", \"orange\", \"grape\"])\n", - "clustered_result = sym_fruits.cluster(metric='cosine', min_cluster_size=2)\n", - "print(f\"Fruit clustering: {clustered_result}\")\n", - "\n", - "sym_sentences = Symbol([\n", - " \"The weather is sunny today.\",\n", - " \"It's raining heavily outside.\",\n", - " \"Beautiful sunny weather today.\"\n", - "])\n", - "sentence_clusters = sym_sentences.cluster(min_cluster_size=2)\n", - "print(f\"Sentence clustering: {sentence_clusters}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 18. Embedding and Similarity Operations\n", - "\n", - "### Embedding Generation (`embed`, `embedding`)" - ] - }, - { - "cell_type": "code", - "execution_count": 60, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Embedding result: ['[-0.00676333112642169, -0.03919631987810135, 0.034175805747509, 0.02876211516559124, -0.02478501945734024, -0.04203926399350166, -0.030289441347122192, 0.04932808503508568, -0.013897152617573738, -0.01764741726219654, 0.015363989397883415, -0.027038201689720154, -0.020974265411496162, -0.027854792773723602, 0.008619560860097408, 0.035627517849206924, -0.05368323251605034, -0.0022720859851688147, 0.008808586746454239, 0.04799734428524971, 0.03710947930812836, -0.009247126057744026, -0.008778342977166176, 0.011402016505599022, 0.014078617095947266, -0.0021624513901770115, -0.03756314143538475, 0.04542659968137741, 0.011250795796513557, -0.03964998200535774, 0.02345428057014942, -0.050628580152988434, 0.012044702656567097, -1.5505995179410093e-05, 0.0160293597728014, 0.006135766394436359, 0.03196798637509346, 0.00336087285540998, -0.008604438975453377, -0.01055518165230751, -0.037381675094366074, -0.034508489072322845, 0.04999345541000366, 0.019371328875422478, -0.014275203458964825, 0.015265696682035923, -0.05434860289096832, 0.05041687190532684, 0.04542659968137741, 0.05371347442269325, -0.0015405575977638364, 0.018524495884776115, 0.0355670303106308, 0.11595578491687775, -0.013262026943266392, -0.040920231491327286, 0.013383002951741219, 0.04769490659236908, -0.014948133379220963, 0.024679165333509445, 0.03217969462275505, 0.013360319659113884, 0.017027413472533226, 0.024845506995916367, 0.013383002951741219, 0.008990051224827766, -0.02436160109937191, -0.00039435437065549195, -0.000644576852209866, 0.05386469513177872, -0.0025140387006103992, 0.03774460405111313, -0.018705960363149643, -0.011507870629429817, -0.0351133719086647, -0.01134908851236105, -0.036686062812805176, 0.004158560186624527, 0.015265696682035923, -0.052292004227638245, -0.03426653519272804, 0.0053910063579678535, -0.021488415077328682, -0.0629681646823883, -0.012384948320686817, 0.03042553924024105, -0.04645489901304245, 0.002824040362611413, -0.0015963200712576509, -0.03692801669239998, 0.01318641658872366, 0.014471789821982384, 0.0005722746136598289, 0.04321878403425217, 0.023272816091775894, 0.00993517879396677, -0.009783958084881306, 0.04191828891634941, 0.06266572326421738, -0.005984546151012182, 0.03868217021226883, -0.024694286286830902, 0.02197232097387314, -0.002841052832081914, 0.026009904220700264, 0.03414556011557579, -0.01226397231221199, -0.0475134402513504, -0.0329962857067585, 0.023998672142624855, -0.11752847582101822, -0.0002967699838336557, -0.012112751603126526, -0.038954365998506546, 0.0063210115768015385, 0.05607251450419426, 0.08885709196329117, -0.07427944988012314, 0.020762557163834572, -0.04709002375602722, 0.029200654476881027, -0.01220348384231329, -0.020762557163834572, -0.046091970056295395, -0.07101308554410934, -0.012747877277433872, -0.013088122941553593, 0.04128316044807434, -0.036262646317481995, -0.005099907051771879, 0.014524716883897781, 0.030909443274140358, 0.0010377498110756278, -0.01757180690765381, -0.023696232587099075, 0.008498584851622581, -0.05223151668906212, -0.014933011494576931, -0.02721966616809368, 0.05304810777306557, 0.06714184582233429, -0.035415809601545334, -0.004381610080599785, -0.03034992888569832, -0.003854229347780347, -0.028580650687217712, -0.015968870371580124, 0.04037583991885185, -0.011061769910156727, 0.0027937963604927063, 0.029351873323321342, 0.03834948688745499, -0.06003448739647865, 0.020777679979801178, 0.004158560186624527, 0.007065772078931332, 0.030319685116410255, -0.041010964661836624, -0.006963698193430901, 0.032119207084178925, 0.002903431188315153, 0.004627343267202377, -0.06051839143037796, -0.00822638813406229, -0.013201538473367691, -0.006528939586132765, -0.02064158022403717, 0.0017494306666776538, -0.04461000859737396, 0.002822150243446231, 0.010540059767663479, -0.0024611116386950016, -0.03214945271611214, -0.04448903352022171, 0.015711797401309013, 0.005258688237518072, 0.03199823200702667, -0.0587339922785759, -0.03004748746752739, -0.03320799395442009, 0.05407640337944031, 0.06956136971712112, 0.011167624033987522, 0.002328793751075864, -0.03390360623598099, -0.014086177572607994, 0.017027413472533226, -0.013541784137487411, 0.010109081864356995, 0.02218402922153473, -0.04448903352022171, 0.06405694782733917, 0.03103042021393776, 0.003699228400364518, 0.002302330220118165, -0.03735143318772316, 0.0840180367231369, 0.021397681906819344, -0.01512959785759449, 0.03632313385605812, -0.0019129377324134111, -0.011054209433495998, -0.028111867606639862, -0.016483020037412643, -0.021821100264787674, -0.026826493442058563, -0.006105522625148296, 0.06339158117771149, 0.006177352275699377, -0.034206047654151917, 0.058280330151319504, -0.0055497875437140465, -0.034508489072322845, -0.004389171488583088, -0.025284046307206154, -0.0007504310924559832, 0.04125291854143143, 0.011628846637904644, 0.01055518165230751, -0.040920231491327286, -0.044942695647478104, 0.08504633605480194, 0.07155747711658478, -0.017148390412330627, 0.032845064997673035, -1.9759068891289644e-05, 0.020611336454749107, 0.007621506694704294, 0.04055730253458023, 0.02718942239880562, 0.026221612468361855, 0.016135213896632195, 0.031302616000175476, -0.04491245001554489, -0.0023628182243555784, -0.010056154802441597, 0.03735143318772316, -0.021851344034075737, -0.021306950598955154, -0.008937124162912369, -0.04330951347947121, 0.01153811439871788, 0.021427927538752556, 0.014766668900847435, 0.03360116481781006, -0.025843560695648193, -0.019371328875422478, -0.026811372488737106, -0.0042568533681333065, 0.013813980855047703, 0.008060045540332794, 0.055709585547447205, -0.006438207346946001, -0.005107467994093895, 0.028399186208844185, -0.006215157452970743, -0.013451051898300648, -0.0046008797362446785, 0.07482384145259857, -0.014880084432661533, -0.037290941923856735, -0.04902564361691475, -0.026992836967110634, -0.03798655793070793, -0.04554757475852966, -0.02649380825459957, -0.001419581240043044, -0.010290546342730522, 0.01577228493988514, -0.009269808419048786, 0.03980120271444321, -0.021473292261362076, 0.06018570810556412, -0.038440220057964325, -0.00187229725997895, 0.005096126347780228, 0.016558630391955376, -0.006131986156105995, -0.020142553374171257, 0.00961761549115181, -0.018993278965353966, 0.0011993665248155594, -0.004332463722676039, 0.018705960363149643, -0.04530562460422516, 0.002151109743863344, 0.037623628973960876, 0.0006025186739861965, 0.0367465503513813, -0.0061546689830720425, 0.019945967942476273, 0.036262646317481995, 0.029729925096035004, 0.00101223133970052, -0.0001459040358895436, 0.020838167518377304, 0.019809868186712265, 0.0012900987640023232, 0.023711353540420532, -0.0524129793047905, 0.06339158117771149, -0.014267642050981522, -0.004585757851600647, 0.0266752727329731, -0.008959807455539703, 0.0288982130587101, 0.032421648502349854, -0.05507446080446243, 0.05050760507583618, 0.0179044920951128, -0.03756314143538475, 0.029200654476881027, 0.04022461920976639, 0.003266360145062208, -0.000645521970000118, -0.048057835549116135, 0.0012305558193475008, -0.030924566090106964, 0.0002452605403959751, -0.05232224985957146, 0.028414307162165642, -0.04457976669073105, -0.021609392017126083, 4.0108840039465576e-05, 0.020490359514951706, -0.0060601565055549145, 0.04222072660923004, -0.006407963111996651, -0.021427927538752556, -0.004033803474158049, -0.018569862470030785, -0.04932808503508568, -0.00487307645380497, 0.011938848532736301, 0.010199814103543758, -0.0049449061043560505, -0.03934754058718681, 0.02965431474149227, -0.006483573466539383, 0.02717430144548416, -0.03124212846159935, -0.027506984770298004, 0.016089847311377525, -0.01072908565402031, -0.017768394201993942, 0.0014791243011131883, 0.059217896312475204, -0.0444587878882885, 0.0078105321153998375, -0.010706402361392975, -0.008067606948316097, 0.01717863418161869, -0.0015235452447086573, -0.017163511365652084, 0.013602272607386112, -0.024240626022219658, 0.022199150174856186, -0.017360098659992218, -0.011296161450445652, 0.047120269387960434, -0.02555624209344387, -0.029094800353050232, 0.0020717191509902477, -0.005863570142537355, 0.048057835549116135, 0.015621064230799675, -0.02380208671092987, -0.06042766198515892, 0.018327908590435982, 0.04300707206130028, 0.000593067379668355, 0.0054552750661969185, 0.025919171050190926, -0.01134908851236105, -0.04654563218355179, -0.03266359865665436, 0.004846612922847271, 0.007451383862644434, 0.045638307929039, -0.008173461072146893, 0.01001834962517023, -0.02277378737926483, -0.011250795796513557, -0.022788910195231438, 0.003837216878309846, -0.0012003117008134723, 0.020777679979801178, 0.0058106426149606705, 0.0008553402149118483, -0.0308943223208189, 0.0807516798377037, -0.027930403128266335, 0.018494252115488052, 0.009504199959337711, 0.01876644790172577, -0.029896266758441925, -0.0026992836501449347, -0.00013763416791334748, -0.017329854890704155, -0.01970401406288147, 0.03163530305027962, -0.0313631035387516, 0.017707904800772667, 0.0008104466833174229, -0.052110541611909866, -0.03302652761340141, -0.014237398281693459, 0.03187725320458412, 0.012505924329161644, -0.02017279714345932, 0.007390895858407021, -0.022804033011198044, 0.034599222242832184, 0.0339338518679142, -0.037290941923856735, -0.01755668595433235, -0.009708347730338573, -0.034720197319984436, -0.007564798928797245, 0.0067595504224300385, 0.012377387844026089, 0.022713299840688705, -0.017496196553111076, 0.03438751399517059, -0.03287531062960625, 0.05888521298766136, 0.05773593857884407, -0.018388397991657257, 0.02419525943696499, -0.07077113538980484, -0.02222939394414425, -0.011099575087428093, -0.042976830154657364, 0.0025801975280046463, 0.012921780347824097, -0.036141667515039444, -0.001595374895259738, 4.4952619646210223e-05, 0.03868217021226883, 0.00228720810264349, 0.013624955900013447, 0.011719578877091408, -0.021261584013700485, -0.034085072576999664, -0.00788614246994257, -0.04252316802740097, -0.013617394492030144, -0.0013468064134940505, -0.022879641503095627, -0.019719136878848076, 0.029593827202916145, -0.06968234479427338, 0.03592995926737785, 0.02384745329618454, -0.0033476410899311304, -0.0020830605644732714, -0.012906658463180065, 0.01393495686352253, -0.021654756739735603, 0.03877290338277817, 0.005795520730316639, 0.0011974762892350554, -0.06357304751873016, 0.04999345541000366, 0.02487575076520443, 0.003574471455067396, 0.0073719932697713375, -0.0026841615326702595, 0.0031321519054472446, -0.03447824344038963, -0.01661911979317665, -0.015084232203662395, 0.03302652761340141, -0.024558188393712044, -0.02564697526395321, 0.00043924793135374784, -0.031393349170684814, 0.02089865505695343, -0.014275203458964825, -0.013110806234180927, 0.007848337292671204, -0.012921780347824097, 0.0044988058507442474, -0.005326737649738789, 0.006426865700632334, 0.05462079867720604, -0.04073876887559891, -0.014411301352083683, -0.016377165913581848, -0.0030244074296206236, -0.01850937306880951, 0.06163742393255234, 0.036655817180871964, -0.01991572231054306, -0.008944684639573097, -0.038016799837350845, 0.006502476055175066, -0.025541121140122414, 0.0027484302408993244, -0.02906455472111702, -0.009753714315593243, -0.03701874613761902, -0.015651308000087738, -0.013125928118824959, 0.05567933991551399, -0.015205208212137222, -0.03840997442603111, -0.02445233426988125, 0.05295737460255623, -0.036686062812805176, -0.04627343267202377, 0.013088122941553593, 0.0023817208129912615, -0.01940157450735569, -0.019552793353796005, -0.006555403117090464, -0.013897152617573738, 0.020883534103631973, -0.0024157455191016197, -0.03632313385605812, 0.008392730727791786, 0.040708523243665695, -0.014880084432661533, -0.029926512390375137, 0.021125486120581627, 0.026100635528564453, -0.04270463436841965, -0.03568800911307335, -0.021957198157906532, 0.023817207664251328, -0.0014158007688820362, -0.016483020037412643, 0.029775291681289673, -0.007602604106068611, -0.014494473114609718, -0.024240626022219658, -0.006290767341852188, 0.014176909811794758, -0.003056541783735156, -0.04324902594089508, 0.000268888717982918, 0.013677882961928844, 0.019220110028982162, 0.007496749982237816, -0.019477182999253273, 0.028610894456505775, 0.04947930574417114, 0.014675936661660671, 0.004041364416480064, 0.037926070392131805, -0.007024186197668314, -0.02662990801036358, -0.020747434347867966, -0.008173461072146893, 0.022168906405568123, -0.009693225845694542, -0.010509815998375416, 0.0003397732798475772, -0.015469844453036785, 0.05419738218188286, 0.023514768108725548, 0.017768394201993942, 0.02042987197637558, -0.003924168646335602, 0.007576140575110912, 0.030848955735564232, -0.017768394201993942, -0.024558188393712044, -0.025707462802529335, -0.035748496651649475, -0.01858498342335224, -0.035627517849206924, -0.01701229251921177, -0.06593208014965057, 0.011764944531023502, -0.0027068445924669504, 0.009156393818557262, 0.04004315286874771, 0.020565969869494438, -0.007107357494533062, -0.01174982264637947, -0.038742657750844955, -0.0498422347009182, 0.02127670682966709, -0.050961267203092575, 0.05068906769156456, 0.021805977448821068, -0.0010075056925415993, 0.01525813527405262, -0.012883976101875305, 0.011719578877091408, 0.011764944531023502, 0.04482171684503555, 0.01258909609168768, -0.036867525428533554, -0.030198708176612854, 0.013821542263031006, 0.005534665659070015, -0.022804033011198044, -0.007088454905897379, 0.013919834978878498, 0.006218937691301107, 0.029941633343696594, -0.0554676316678524, 0.015484966337680817, -0.026040147989988327, -0.020505482330918312, -0.008309559896588326, 0.025495754554867744, -0.051566146314144135, -0.026100635528564453, 0.0323006696999073, 0.003931729588657618, -0.04076901078224182, -0.018358152359724045, 0.027960646897554398, -0.022894764319062233, 0.007296382915228605, 0.005905155558139086, -0.0032228841446340084, -0.01841864176094532, -0.047543685883283615, 0.009352980181574821, 0.04285585507750511, 0.008990051224827766, 0.025238679721951485, -0.02008206583559513, 0.004820149391889572, -0.007239675149321556, 0.007999558001756668, 0.02777918241918087, -0.006536500528454781, 0.00033528392668813467, -0.04055730253458023, 0.0007012845017015934, 0.01612009108066559, 0.0066650379449129105, -0.014562522061169147, -0.001597265130840242, -0.03753289580345154, 0.032633356750011444, 0.005311615765094757, 0.009126149117946625, -0.037926070392131805, 0.041222672909498215, 0.020187919959425926, 0.030153341591358185, 0.01267226692289114, 0.006385280285030603, -0.01876644790172577, 0.036655817180871964, 0.02517819218337536, 0.020278651267290115, -0.013685443438589573, 0.026040147989988327, 0.008801025338470936, -0.04321878403425217, -0.026947470381855965, -0.01339812483638525, 0.012702511623501778, -0.012793243862688541, 0.05679837241768837, -0.009095905348658562, -0.022501591593027115, -0.006910771131515503, -0.008445657789707184, -0.0200064554810524, 0.02499672770500183, 0.005701008252799511, -0.018146444112062454, 0.002540502231568098, -0.01628643460571766, 0.047029536217451096, 5.853882248629816e-05, 0.04524513706564903, -0.0012589095858857036, -0.003094346961006522, -0.03777484968304634, -0.0058106426149606705, -0.02812698855996132, 0.0045063672587275505, 0.02747674100100994, -0.040708523243665695, -0.02564697526395321, 0.009322735480964184, 0.022425981238484383, 0.016225945204496384, 0.016422532498836517, -0.004294658545404673, -0.011175185441970825, -0.027461620047688484, -0.014887645840644836, 0.004154779948294163, 0.01713326759636402, -0.008944684639573097, -0.032330915331840515, 0.0332382395863533, 0.007538335397839546, -0.012324460782110691, -0.030319685116410255, 0.015462283045053482, -0.02080792374908924, -0.019628403708338737, -0.006937234662473202, 0.005844667553901672, -0.005360762123018503, -0.01504642702639103, 0.04182755574584007, 0.04551733285188675, 0.00010408214438939467, -0.03269384428858757, -0.016724973917007446, -0.015500088222324848, -0.020021576434373856, -0.034175805747509, 0.003358982503414154, -0.022894764319062233, -0.05413689464330673, 0.009194198995828629, 0.008521268144249916, -0.04179731011390686, 0.0063399141654372215, -0.016301555559039116, -0.004396732430905104, -0.018070833757519722, 0.0089522460475564, -0.016573753207921982, -0.019764503464102745, 0.019809868186712265, 0.012022019363939762, 0.023741599172353745, 0.001742814783938229, 0.0188420582562685, 0.014925451017916203, 0.0027049544733017683, -0.010865183547139168, -0.047422707080841064, -0.019734257832169533, -0.013950079679489136, -0.0402548648416996, -0.006502476055175066, -0.004018681589514017, 0.022335248067975044, 0.0367465503513813, -0.022289883345365524, 0.0027068445924669504, -0.013254465535283089, 0.016437655314803123, -0.03716996684670448, 0.011840554885566235, -0.01523545291274786, 0.013511540368199348, -0.004415635019540787, 0.001920498674735427, 0.003194530261680484, -0.044942695647478104, -0.005942960735410452, 0.0013817761791869998, -0.001612387248314917, 0.029805535450577736, -0.016770338639616966, 0.03166554495692253, -0.006101741921156645, 0.019084010273218155, 0.010577864944934845, 0.013284709304571152, 0.02440696768462658, -0.01358715072274208, 0.0027030641213059425, 0.006638574413955212, 0.03735143318772316, -0.012581534683704376, 0.041525114327669144, 0.0035177639219909906, 0.002353366930037737, -0.036686062812805176, -0.02239573746919632, 0.00781809352338314, -0.023045985028147697, 0.005179297644644976, -0.03260311111807823, 0.004132096655666828, -0.018479129299521446, -0.006615891121327877, 0.018690837547183037, -0.03296604007482529, 0.0034137999173253775, 0.007931508123874664, 0.019386451691389084, -0.038863636553287506, -0.006241620983928442, -0.016271311789751053, -0.007795410230755806, -0.018010346218943596, 0.014963256195187569, 0.04206950590014458, -0.006846502423286438, -0.04182755574584007, 0.017768394201993942, 0.004589538089931011, -0.001226775231771171, -0.010434205643832684, 0.041736822575330734, 0.017072780057787895, -0.012014458887279034, -0.037926070392131805, -0.008876635693013668, 0.026766005903482437, -0.007916386239230633, 0.008672487922012806, 0.0054666162468492985, 0.043702688068151474, -0.01940157450735569, 0.002149219624698162, -0.021942075341939926, -0.057554472237825394, 0.010933232493698597, -0.014365935698151588, 0.0035877032205462456, 0.01305787917226553, 0.004287097603082657, -0.008929562754929066, -0.04896515607833862, -0.04013388603925705, 0.03384311869740486, 0.018736204132437706, -0.020399628207087517, 0.009708347730338573, 0.020112309604883194, -0.0098293237388134, 0.004631123971194029, -0.0033325189724564552, -0.019885478541254997, -0.01098616048693657, 0.01769278384745121, 0.05235249176621437, -0.008082728832960129, -0.03520410135388374, -0.03115139715373516, -0.017798637971282005, -0.0027843450661748648, -0.012279094196856022, 0.004827710334211588, -0.02136743813753128, 0.040406081825494766, -0.0008983435109257698, 0.014781791716814041, -0.02499672770500183, -0.014154226519167423, 0.023998672142624855, -0.01453227736055851, -0.014426423236727715, 0.0489046685397625, 0.011840554885566235, -0.022078175097703934, 0.010592986829578876, -0.035960204899311066, -0.015114475972950459, -0.018176687881350517, -0.01633179932832718, -0.013367881067097187, 0.035627517849206924, 0.016694728285074234, -0.0009389839833602309, 0.02321232669055462, -0.01466081477701664, -0.007700897287577391, 0.013413246721029282, 0.015288379974663258, 0.03726070001721382, 0.02688698284327984, 0.01271763350814581, -0.004003559239208698, -0.010517376475036144, 0.03550654277205467, 0.03565776348114014, -0.03850070759654045, 0.0023930624593049288, -0.012513485737144947, -0.027703572064638138, 0.025495754554867744, 0.010706402361392975, 0.000559515377972275, -0.022456225007772446, -0.01661911979317665, -0.024890873581171036, -0.016951803117990494, 0.017632296308875084, 0.021427927538752556, -0.014260080642998219, -0.0003952995175495744, -0.003710569813847542, 0.0008595932740718126, -0.0226981770247221, 0.012142996303737164, 0.014743986539542675, -0.02157914638519287, 0.022531835362315178, 0.010033471509814262, 0.016891315579414368, -0.012271532788872719, -0.010464449413120747, 0.007802971173077822, 0.007277480326592922, 0.0005996832624077797, 0.015560576692223549, -0.004672709386795759, 0.004495025612413883, 0.014925451017916203, 0.00886907521635294, -0.01640740968286991, -0.037593383342027664, 0.014766668900847435, -0.007224553264677525, 0.04896515607833862, 0.012256410904228687, -0.0014110751217231154, 0.03217969462275505, 0.018600106239318848, 0.0226981770247221, -0.01042664423584938, -0.04439830034971237, -0.007421139627695084, 0.012324460782110691, -0.001315617235377431, 0.009715909138321877, -0.04624319076538086, 0.04823929816484451, -0.0038258754648268223, 0.0014176910044625401, 0.032421648502349854, 0.009625176899135113, -0.012679828330874443, 0.0098293237388134, 0.01406349427998066, -0.009844446554780006, -0.03363141044974327, 0.029155287891626358, -0.025994781404733658, -0.023832330480217934, -0.026312345638871193, 0.02218402922153473, 0.010517376475036144, 0.0064344266429543495, 0.03964998200535774, 0.013624955900013447, 0.010804696008563042, 0.009685664437711239, 0.0035253248643130064, -0.0013042757054790854, -0.03278457745909691, -0.0003752155462279916, 0.026735762134194374, 0.0010821707546710968, -0.02564697526395321, -0.002047145739197731, 0.048571985214948654, -0.0012324460549280047, 0.008937124162912369, 0.010381278581917286, -0.005277590826153755, -0.012324460782110691, -0.004846612922847271, -0.01773815043270588, -0.006290767341852188, -0.015878139063715935, -0.029986999928951263, -0.025783073157072067, 0.019794747233390808, 0.006343694403767586, -0.011515431106090546, -0.002521599642932415, 0.021337194368243217, 0.007848337292671204, -0.0020811704453080893, -0.0008898373926058412, -0.0054855188354849815, 0.02602502517402172, 0.04064803570508957, 0.009262247942388058, 0.010910550132393837, 0.012944463640451431, 0.02153378166258335, -0.017919614911079407, -0.01893279142677784, -0.0013761053560301661, 0.012294216081500053, 0.018690837547183037, -0.024225503206253052, -0.005402348004281521, -0.010948355309665203, -0.005319176707416773, -0.037079233676195145, 0.03236116096377373, 0.005572470836341381, -0.027809426188468933, -0.026297222822904587, 0.0048806373961269855, -0.03320799395442009, 0.011500309221446514, 0.026040147989988327, 0.03538556769490242, 0.016936682164669037, 0.00942102912813425, 0.025495754554867744, 0.025329412892460823, -0.015605942346155643, 0.018615227192640305, 0.001165341935120523, -0.0043400246649980545, 0.031907498836517334, 0.01760205067694187, -0.031090907752513885, 0.004309780430048704, 0.01360983308404684, 0.01661911979317665, -0.029155287891626358, 0.027234788984060287, -0.005856008734554052, -0.0088917575776577, -0.0006181132630445063, -0.0008099740953184664, 0.005394786596298218, -0.01785912550985813, 0.0027881255373358727, -0.014985938556492329, 0.01432056911289692, 0.00814321730285883, 0.0061433278024196625, 0.03701874613761902, -0.0160293597728014, 0.0035877032205462456, -0.011311284266412258, 0.03644410893321037, 0.00778784928843379, 0.03901485726237297, -0.016770338639616966, -0.01909913308918476, -0.03559727594256401, 0.011961531825363636, -0.0033003846183419228, -0.011976653710007668, -0.006101741921156645, -0.01584789529442787, 0.0013108915882185102, 0.005874911323189735, -0.013987884856760502, 0.020490359514951706, 0.003464836860075593, -0.006290767341852188, -0.02752210758626461, 0.001937511027790606, -0.023061105981469154, 0.004260634072124958, 0.007670653518289328, 0.024890873581171036, 0.032633356750011444, -0.0016426312504336238, -0.012664706446230412, 0.017919614911079407, -0.0465758740901947, -0.015742041170597076, -0.047755394130945206, 0.002712515415623784, 0.029246019199490547, -0.029593827202916145, 0.0100637162104249, 0.021609392017126083, 0.010282984934747219, 0.030803589150309563, -0.01147762592881918, 0.011212990619242191, -0.003557459218427539, 0.039680223912000656, 0.00995786115527153, -0.02824796549975872, 0.006838941480964422, -0.011386893689632416, 0.009927617385983467, -0.005602714605629444, 0.006131986156105995, -0.009526883251965046, 0.02029377408325672, -0.042462680488824844, -0.03710947930812836, -0.01914449967443943, 0.033359214663505554, -0.011137380264699459, 0.02684161625802517, 0.022849397733807564, -0.004211487248539925, -0.0012787572341039777, -0.010736646130681038, -0.014827157370746136, -0.04285585507750511, 0.004120755009353161, 0.018947912380099297, 0.022667933255434036, 0.039045099169015884, -0.012483241967856884, -0.01572691835463047, 0.03281481936573982, 0.0013515320606529713, -0.012528607621788979, -0.008120534010231495, 0.011137380264699459, 0.0023741598706692457, -0.0070582106709480286, -0.008407852612435818, 0.009799079969525337, 0.0032569088507443666, -0.006305889692157507, -0.007893703877925873, -0.0015405575977638364, 0.008922002278268337, -0.016437655314803123, -0.023303059861063957, -0.019673770293593407, -0.00029204433667473495, -0.02124646306037903, 0.007421139627695084, -0.03145383670926094, 0.025163069367408752, 0.0027673328295350075, -0.007462725508958101, 0.014010567218065262, 0.04191828891634941, 0.006290767341852188, -0.03308701887726784, 0.004317341838032007, -0.006313450634479523, 0.003247457556426525, 0.023257693275809288, -0.03856119513511658, 0.019552793353796005, 0.05038662627339363, -0.030138220638036728, -0.00339678768068552, -0.024709409102797508, 0.02085328847169876, 0.04249292612075806, -0.01850937306880951, -0.0006970313843339682, -0.011681773699820042, -0.022622568532824516, -0.010676158592104912, -0.001289153704419732, 0.12139971554279327, -0.03680703788995743, -0.029593827202916145, 0.017874248325824738, 0.036050938069820404, 0.002090621739625931, -0.014774230308830738, 0.004449659492820501, 0.001894980319775641, -0.0039052660576999187, -0.006691501475870609, -0.034296780824661255, -0.03889387845993042, -0.019840111956000328, -0.0044534397311508656, 0.03961973637342453, -0.005530884955078363, -0.03266359865665436, -0.009481517598032951, -0.017768394201993942, 0.01636204496026039, -0.04261390119791031, -0.0017598271369934082, 0.0036273987498134375, -0.002950687427073717, -0.025964537635445595, -0.025677219033241272, -0.009640298783779144, 0.0038863634690642357, 0.058703746646642685, 0.019416695460677147, 0.0026784909423440695, 0.015787407755851746, 0.008853952400386333, -0.004657587502151728, 0.0307733453810215, -0.030440660193562508, -0.02936699613928795, -0.031211884692311287, 0.005383445415645838, -0.03756314143538475, -0.0004727999330498278, 0.03151432424783707, -0.02017279714345932, -0.0024403186980634928, -0.005685885902494192, 0.014554960653185844, 0.0007390895625576377, 0.005243566352874041, -0.00933785829693079, -0.01755668595433235, 0.044640254229307175, -0.004438317846506834, 0.011235673911869526, 0.009073222056031227, 0.001162506639957428, 0.015061548911035061, 0.02487575076520443, 0.05580031871795654, -7.63190328143537e-05, -0.0024630017578601837, -0.009058100171387196, 0.028731871396303177, 0.022244516760110855, 0.001828821375966072, -0.013791297562420368, -0.013042757287621498, 0.02431623637676239, -0.02829333208501339, 0.03047090582549572, 0.00392038794234395, 0.011802749708294868, 0.016135213896632195, 0.026781128719449043, 0.02948797307908535, 0.0348714180290699, -0.047210998833179474, -0.002757881535217166, -0.02316696010529995, 0.0050923461094498634, 0.002062267856672406, -0.014373496174812317, 0.012082507833838463, 0.023983551189303398, 0.02466404251754284, 0.01100884284824133, 0.011212990619242191, 0.02026353031396866, -0.026312345638871193, -0.01271763350814581, 0.006094180978834629, 6.645426765317097e-05, 0.006381499581038952, -0.02157914638519287, 0.006706623360514641, 0.013299832120537758, -0.04424707964062691, 0.017707904800772667, 0.006479792762547731, 0.005277590826153755, 0.023923063650727272, 0.013352759182453156, 0.009156393818557262, 0.02346940152347088, -0.004018681589514017, -0.019930845126509666, 0.0009645024547353387, -0.03538556769490242, -0.04182755574584007, 0.012422753497958183, -0.003122700611129403, -0.012793243862688541, 0.002992273075506091, 0.015288379974663258, 0.020611336454749107, -0.06859356164932251, -0.03629288822412491, -0.015348867513239384, -0.0022361711598932743, 0.0013468064134940505, 0.04572904109954834, 0.023711353540420532, -0.00011867254943354055, -0.023393791168928146, 0.041948530822992325, -0.016694728285074234, 0.047120269387960434, 0.01610497012734413, 0.04397488385438919, -0.023741599172353745, 0.011583480052649975, -0.014025689102709293, 0.021185973659157753, 0.01053249929100275, -0.005753935314714909, 0.012090068310499191, 0.01820693351328373, -0.02859577164053917, 0.012558852322399616, 0.014055933803319931, 0.013050317764282227, -0.03157481551170349, -0.001053816988132894, -0.01346617378294468, -0.0014536058297380805, 0.015432039275765419, 0.0498422347009182, 0.013375441543757915, -0.018312787637114525, -0.042371947318315506, -0.03133286163210869, -0.018736204132437706, 0.0025575144682079554, -0.02653917483985424, -0.00237226951867342, 0.006623452063649893, -0.035234346985816956, -0.011311284266412258, 0.004245511721819639, -0.018327908590435982, -0.0188420582562685, -0.009352980181574821, 0.01047201082110405, -0.008732976391911507, -0.01581765152513981, 0.00680491654202342, -0.029079677537083626, 0.002519709523767233, -0.03251238167285919, -0.0069258930161595345, 0.048874422907829285, -0.041555359959602356, -0.01226397231221199, 0.03747240826487541, 0.039680223912000656, -0.014139104634523392, 0.00762906763702631, 0.008218827657401562, 0.02321232669055462, 0.005081004463136196, -0.049509551376104355, -0.04333975911140442, 0.026690395548939705, -0.02162451297044754, -0.016558630391955376, 0.026569418609142303, -0.027537230402231216, -0.0011738481698557734, -0.0003797048993874341, -0.044851962476968765, 0.007175406441092491, -0.015621064230799675, -0.0024384285788983107, -0.006865405011922121, -0.022123539820313454, -0.028217721730470657, -0.032754331827163696, -0.049086131155490875, -0.0024837946984916925, -0.009247126057744026, -0.024165015667676926, -0.03565776348114014, 0.0061622303910553455, 0.01260421797633171, -0.0001532287715235725, 0.011341528035700321, -0.016679607331752777, 0.0100032277405262, -0.015953749418258667, -0.01098616048693657, 0.01940157450735569, 0.018403518944978714, -0.018600106239318848, -0.001313726999796927, 0.050114430487155914, 0.06069985777139664, 0.010971037670969963, 0.008581755682826042, 0.009005173109471798, -0.0017683332553133368, -0.004200145602226257, -0.007723580580204725, 0.028429429978132248, -0.011757384054362774, -0.018055712804198265, 0.02368110977113247, 0.002863735891878605, -0.027234788984060287, -0.019053766503930092, -0.007077113259583712, 0.04467049613595009, 0.02064158022403717, 0.012513485737144947, 0.02855040691792965, -0.011402016505599022, 0.01106933131814003, -0.0069447956047952175, 0.005481738597154617, 0.0014829047722741961, -0.007553457748144865, -0.0044874646700918674, -0.030879199504852295, 0.0007438152097165585, -0.0074022370390594006, -0.012437875382602215, 0.017329854890704155, 0.04715051129460335, -0.020717190578579903, 0.018025469034910202, 0.005326737649738789, 0.007470286451280117, 0.03753289580345154, -0.017934735864400864, -0.012029580771923065, -0.002107633976265788, -0.005447714123874903, 0.012762999162077904, 0.0029204434249550104, 0.02466404251754284, -0.005572470836341381, -0.0298357792198658, -0.0037748385220766068, 0.01586301624774933, -0.02244110405445099, 0.012967146933078766, -0.01940157450735569, 0.021805977448821068, 0.023786963894963264, 0.01264958456158638, 0.02042987197637558, -0.00344593427143991, -0.009239564649760723, 0.01654350943863392, -0.011825433000922203, -0.01846400834619999, 0.03224018216133118, 0.020248407498002052, -0.013299832120537758, 0.013677882961928844, -0.011885921470820904, -0.02372647635638714, -0.031090907752513885, -0.013640077784657478, -0.004884418100118637, -0.015469844453036785, -0.011228112503886223, 0.009065661579370499, 0.006150888744741678, -0.023832330480217934, 0.008249071426689625, 0.060881320387125015, -0.00021537089196499437, 0.002865626011043787, 0.008196144364774227, 0.006449548993259668, 0.0241045281291008, -0.005776618141680956, 0.034085072576999664, 0.031121153384447098, -0.008218827657401562, -0.023136716336011887, -0.00037946863449178636, 0.02405916154384613, -0.022501591593027115, -0.010207375511527061, 0.013246904127299786, 0.028414307162165642, 0.0009399291011504829, -0.008377608843147755, -0.022168906405568123, -0.005538445897400379, 0.018705960363149643, 0.0017579367849975824, -0.008559073321521282, 0.0006058266153559089, 0.008725415915250778, -0.018524495884776115, 0.021851344034075737, -0.021911831572651863, 0.04016413167119026, 0.03381287679076195, 0.011061769910156727, 0.006011009681969881, 0.020203040912747383, -0.006525158882141113, -0.0320587195456028, 0.008551511913537979, -0.024694286286830902, 0.020157676190137863, -0.030062610283493996, 0.019250353798270226, 0.001834492082707584, 0.0577964261174202, -0.028837725520133972, 0.02295525185763836, -0.009647860191762447, -0.011175185441970825, -0.008702732622623444, 0.025011848658323288, -0.023514768108725548, 0.013534223660826683, 0.020157676190137863, -0.008687610737979412, 0.02675088308751583, 0.013662761077284813, 0.007647970225661993, 0.025783073157072067, -0.016558630391955376, -0.016603996977210045, 0.015295940451323986, -0.023650866001844406, 0.00995786115527153, 0.009700787253677845, -0.020626459270715714, -0.04829978570342064, 0.010895428247749805, -0.008044923655688763, -0.011908603832125664, -0.0036009352188557386, -0.03366165608167648, -0.03992217779159546, -0.01504642702639103, -0.026690395548939705, -0.009511761367321014, -0.02637283317744732, 0.050023697316646576, -0.039982665330171585, 0.00023344645160250366, 0.010078838095068932, -0.008959807455539703, 0.003515873569995165, -0.0017352537252008915, 0.027416253462433815, -0.029518216848373413, 0.002502697054296732, -0.019462062045931816, 0.010093959979712963, -0.024437211453914642, 0.028474796563386917, 0.010585426352918148, -0.002803247654810548, -0.02991138957440853, 0.006298328284174204, -0.006479792762547731, 0.009708347730338573, 0.01331495400518179, -0.019643526524305344, -0.019371328875422478, -0.022471347823739052]']\n", - "Embedding shape: (1, 1536)\n" - ] - } - ], - "source": [ - "sym_text = Symbol(\"hello world\")\n", - "embedded_result = sym_text.embed()\n", - "print(f\"Embedding result: {embedded_result}\")\n", - "\n", - "# Access embedding property\n", - "embedding_value = sym_text.embedding\n", - "print(f\"Embedding shape: {embedding_value.shape if hasattr(embedding_value, 'shape') else 'N/A'}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Similarity and Distance Calculations" - ] - }, - { - "cell_type": "code", - "execution_count": 61, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Similarity: 0.5092170138827085\n", - "Distance: 0.37472382492017714\n" - ] - } - ], - "source": [ - "sym1 = Symbol(\"hello world\")\n", - "sym2 = Symbol(\"hi there\")\n", - "\n", - "similarity_result = sym1.similarity(sym2, metric='cosine')\n", - "print(f\"Similarity: {similarity_result}\")\n", - "\n", - "distance_result = sym1.distance(sym2, kernel='gaussian')\n", - "print(f\"Distance: {distance_result}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Embedding Packaging (`zip`)" - ] - }, - { - "cell_type": "code", - "execution_count": 62, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Zip result: [('cf52bd7b-ee06-4d28-ba22-7e37e5d99a93', [-0.00676333112642169, -0.03919631987810135, 0.034175805747509, 0.02876211516559124, -0.02478501945734024, -0.04203926399350166, -0.030289441347122192, 0.04932808503508568, -0.013897152617573738, -0.01764741726219654, 0.015363989397883415, -0.027038201689720154, -0.020974265411496162, -0.027854792773723602, 0.008619560860097408, 0.035627517849206924, -0.05368323251605034, -0.0022720859851688147, 0.008808586746454239, 0.04799734428524971, 0.03710947930812836, -0.009247126057744026, -0.008778342977166176, 0.011402016505599022, 0.014078617095947266, -0.0021624513901770115, -0.03756314143538475, 0.04542659968137741, 0.011250795796513557, -0.03964998200535774, 0.02345428057014942, -0.050628580152988434, 0.012044702656567097, -1.5505995179410093e-05, 0.0160293597728014, 0.006135766394436359, 0.03196798637509346, 0.00336087285540998, -0.008604438975453377, -0.01055518165230751, -0.037381675094366074, -0.034508489072322845, 0.04999345541000366, 0.019371328875422478, -0.014275203458964825, 0.015265696682035923, -0.05434860289096832, 0.05041687190532684, 0.04542659968137741, 0.05371347442269325, -0.0015405575977638364, 0.018524495884776115, 0.0355670303106308, 0.11595578491687775, -0.013262026943266392, -0.040920231491327286, 0.013383002951741219, 0.04769490659236908, -0.014948133379220963, 0.024679165333509445, 0.03217969462275505, 0.013360319659113884, 0.017027413472533226, 0.024845506995916367, 0.013383002951741219, 0.008990051224827766, -0.02436160109937191, -0.00039435437065549195, -0.000644576852209866, 0.05386469513177872, -0.0025140387006103992, 0.03774460405111313, -0.018705960363149643, -0.011507870629429817, -0.0351133719086647, -0.01134908851236105, -0.036686062812805176, 0.004158560186624527, 0.015265696682035923, -0.052292004227638245, -0.03426653519272804, 0.0053910063579678535, -0.021488415077328682, -0.0629681646823883, -0.012384948320686817, 0.03042553924024105, -0.04645489901304245, 0.002824040362611413, -0.0015963200712576509, -0.03692801669239998, 0.01318641658872366, 0.014471789821982384, 0.0005722746136598289, 0.04321878403425217, 0.023272816091775894, 0.00993517879396677, -0.009783958084881306, 0.04191828891634941, 0.06266572326421738, -0.005984546151012182, 0.03868217021226883, -0.024694286286830902, 0.02197232097387314, -0.002841052832081914, 0.026009904220700264, 0.03414556011557579, -0.01226397231221199, -0.0475134402513504, -0.0329962857067585, 0.023998672142624855, -0.11752847582101822, -0.0002967699838336557, -0.012112751603126526, -0.038954365998506546, 0.0063210115768015385, 0.05607251450419426, 0.08885709196329117, -0.07427944988012314, 0.020762557163834572, -0.04709002375602722, 0.029200654476881027, -0.01220348384231329, -0.020762557163834572, -0.046091970056295395, -0.07101308554410934, -0.012747877277433872, -0.013088122941553593, 0.04128316044807434, -0.036262646317481995, -0.005099907051771879, 0.014524716883897781, 0.030909443274140358, 0.0010377498110756278, -0.01757180690765381, -0.023696232587099075, 0.008498584851622581, -0.05223151668906212, -0.014933011494576931, -0.02721966616809368, 0.05304810777306557, 0.06714184582233429, -0.035415809601545334, -0.004381610080599785, -0.03034992888569832, -0.003854229347780347, -0.028580650687217712, -0.015968870371580124, 0.04037583991885185, -0.011061769910156727, 0.0027937963604927063, 0.029351873323321342, 0.03834948688745499, -0.06003448739647865, 0.020777679979801178, 0.004158560186624527, 0.007065772078931332, 0.030319685116410255, -0.041010964661836624, -0.006963698193430901, 0.032119207084178925, 0.002903431188315153, 0.004627343267202377, -0.06051839143037796, -0.00822638813406229, -0.013201538473367691, -0.006528939586132765, -0.02064158022403717, 0.0017494306666776538, -0.04461000859737396, 0.002822150243446231, 0.010540059767663479, -0.0024611116386950016, -0.03214945271611214, -0.04448903352022171, 0.015711797401309013, 0.005258688237518072, 0.03199823200702667, -0.0587339922785759, -0.03004748746752739, -0.03320799395442009, 0.05407640337944031, 0.06956136971712112, 0.011167624033987522, 0.002328793751075864, -0.03390360623598099, -0.014086177572607994, 0.017027413472533226, -0.013541784137487411, 0.010109081864356995, 0.02218402922153473, -0.04448903352022171, 0.06405694782733917, 0.03103042021393776, 0.003699228400364518, 0.002302330220118165, -0.03735143318772316, 0.0840180367231369, 0.021397681906819344, -0.01512959785759449, 0.03632313385605812, -0.0019129377324134111, -0.011054209433495998, -0.028111867606639862, -0.016483020037412643, -0.021821100264787674, -0.026826493442058563, -0.006105522625148296, 0.06339158117771149, 0.006177352275699377, -0.034206047654151917, 0.058280330151319504, -0.0055497875437140465, -0.034508489072322845, -0.004389171488583088, -0.025284046307206154, -0.0007504310924559832, 0.04125291854143143, 0.011628846637904644, 0.01055518165230751, -0.040920231491327286, -0.044942695647478104, 0.08504633605480194, 0.07155747711658478, -0.017148390412330627, 0.032845064997673035, -1.9759068891289644e-05, 0.020611336454749107, 0.007621506694704294, 0.04055730253458023, 0.02718942239880562, 0.026221612468361855, 0.016135213896632195, 0.031302616000175476, -0.04491245001554489, -0.0023628182243555784, -0.010056154802441597, 0.03735143318772316, -0.021851344034075737, -0.021306950598955154, -0.008937124162912369, -0.04330951347947121, 0.01153811439871788, 0.021427927538752556, 0.014766668900847435, 0.03360116481781006, -0.025843560695648193, -0.019371328875422478, -0.026811372488737106, -0.0042568533681333065, 0.013813980855047703, 0.008060045540332794, 0.055709585547447205, -0.006438207346946001, -0.005107467994093895, 0.028399186208844185, -0.006215157452970743, -0.013451051898300648, -0.0046008797362446785, 0.07482384145259857, -0.014880084432661533, -0.037290941923856735, -0.04902564361691475, -0.026992836967110634, -0.03798655793070793, -0.04554757475852966, -0.02649380825459957, -0.001419581240043044, -0.010290546342730522, 0.01577228493988514, -0.009269808419048786, 0.03980120271444321, -0.021473292261362076, 0.06018570810556412, -0.038440220057964325, -0.00187229725997895, 0.005096126347780228, 0.016558630391955376, -0.006131986156105995, -0.020142553374171257, 0.00961761549115181, -0.018993278965353966, 0.0011993665248155594, -0.004332463722676039, 0.018705960363149643, -0.04530562460422516, 0.002151109743863344, 0.037623628973960876, 0.0006025186739861965, 0.0367465503513813, -0.0061546689830720425, 0.019945967942476273, 0.036262646317481995, 0.029729925096035004, 0.00101223133970052, -0.0001459040358895436, 0.020838167518377304, 0.019809868186712265, 0.0012900987640023232, 0.023711353540420532, -0.0524129793047905, 0.06339158117771149, -0.014267642050981522, -0.004585757851600647, 0.0266752727329731, -0.008959807455539703, 0.0288982130587101, 0.032421648502349854, -0.05507446080446243, 0.05050760507583618, 0.0179044920951128, -0.03756314143538475, 0.029200654476881027, 0.04022461920976639, 0.003266360145062208, -0.000645521970000118, -0.048057835549116135, 0.0012305558193475008, -0.030924566090106964, 0.0002452605403959751, -0.05232224985957146, 0.028414307162165642, -0.04457976669073105, -0.021609392017126083, 4.0108840039465576e-05, 0.020490359514951706, -0.0060601565055549145, 0.04222072660923004, -0.006407963111996651, -0.021427927538752556, -0.004033803474158049, -0.018569862470030785, -0.04932808503508568, -0.00487307645380497, 0.011938848532736301, 0.010199814103543758, -0.0049449061043560505, -0.03934754058718681, 0.02965431474149227, -0.006483573466539383, 0.02717430144548416, -0.03124212846159935, -0.027506984770298004, 0.016089847311377525, -0.01072908565402031, -0.017768394201993942, 0.0014791243011131883, 0.059217896312475204, -0.0444587878882885, 0.0078105321153998375, -0.010706402361392975, -0.008067606948316097, 0.01717863418161869, -0.0015235452447086573, -0.017163511365652084, 0.013602272607386112, -0.024240626022219658, 0.022199150174856186, -0.017360098659992218, -0.011296161450445652, 0.047120269387960434, -0.02555624209344387, -0.029094800353050232, 0.0020717191509902477, -0.005863570142537355, 0.048057835549116135, 0.015621064230799675, -0.02380208671092987, -0.06042766198515892, 0.018327908590435982, 0.04300707206130028, 0.000593067379668355, 0.0054552750661969185, 0.025919171050190926, -0.01134908851236105, -0.04654563218355179, -0.03266359865665436, 0.004846612922847271, 0.007451383862644434, 0.045638307929039, -0.008173461072146893, 0.01001834962517023, -0.02277378737926483, -0.011250795796513557, -0.022788910195231438, 0.003837216878309846, -0.0012003117008134723, 0.020777679979801178, 0.0058106426149606705, 0.0008553402149118483, -0.0308943223208189, 0.0807516798377037, -0.027930403128266335, 0.018494252115488052, 0.009504199959337711, 0.01876644790172577, -0.029896266758441925, -0.0026992836501449347, -0.00013763416791334748, -0.017329854890704155, -0.01970401406288147, 0.03163530305027962, -0.0313631035387516, 0.017707904800772667, 0.0008104466833174229, -0.052110541611909866, -0.03302652761340141, -0.014237398281693459, 0.03187725320458412, 0.012505924329161644, -0.02017279714345932, 0.007390895858407021, -0.022804033011198044, 0.034599222242832184, 0.0339338518679142, -0.037290941923856735, -0.01755668595433235, -0.009708347730338573, -0.034720197319984436, -0.007564798928797245, 0.0067595504224300385, 0.012377387844026089, 0.022713299840688705, -0.017496196553111076, 0.03438751399517059, -0.03287531062960625, 0.05888521298766136, 0.05773593857884407, -0.018388397991657257, 0.02419525943696499, -0.07077113538980484, -0.02222939394414425, -0.011099575087428093, -0.042976830154657364, 0.0025801975280046463, 0.012921780347824097, -0.036141667515039444, -0.001595374895259738, 4.4952619646210223e-05, 0.03868217021226883, 0.00228720810264349, 0.013624955900013447, 0.011719578877091408, -0.021261584013700485, -0.034085072576999664, -0.00788614246994257, -0.04252316802740097, -0.013617394492030144, -0.0013468064134940505, -0.022879641503095627, -0.019719136878848076, 0.029593827202916145, -0.06968234479427338, 0.03592995926737785, 0.02384745329618454, -0.0033476410899311304, -0.0020830605644732714, -0.012906658463180065, 0.01393495686352253, -0.021654756739735603, 0.03877290338277817, 0.005795520730316639, 0.0011974762892350554, -0.06357304751873016, 0.04999345541000366, 0.02487575076520443, 0.003574471455067396, 0.0073719932697713375, -0.0026841615326702595, 0.0031321519054472446, -0.03447824344038963, -0.01661911979317665, -0.015084232203662395, 0.03302652761340141, -0.024558188393712044, -0.02564697526395321, 0.00043924793135374784, -0.031393349170684814, 0.02089865505695343, -0.014275203458964825, -0.013110806234180927, 0.007848337292671204, -0.012921780347824097, 0.0044988058507442474, -0.005326737649738789, 0.006426865700632334, 0.05462079867720604, -0.04073876887559891, -0.014411301352083683, -0.016377165913581848, -0.0030244074296206236, -0.01850937306880951, 0.06163742393255234, 0.036655817180871964, -0.01991572231054306, -0.008944684639573097, -0.038016799837350845, 0.006502476055175066, -0.025541121140122414, 0.0027484302408993244, -0.02906455472111702, -0.009753714315593243, -0.03701874613761902, -0.015651308000087738, -0.013125928118824959, 0.05567933991551399, -0.015205208212137222, -0.03840997442603111, -0.02445233426988125, 0.05295737460255623, -0.036686062812805176, -0.04627343267202377, 0.013088122941553593, 0.0023817208129912615, -0.01940157450735569, -0.019552793353796005, -0.006555403117090464, -0.013897152617573738, 0.020883534103631973, -0.0024157455191016197, -0.03632313385605812, 0.008392730727791786, 0.040708523243665695, -0.014880084432661533, -0.029926512390375137, 0.021125486120581627, 0.026100635528564453, -0.04270463436841965, -0.03568800911307335, -0.021957198157906532, 0.023817207664251328, -0.0014158007688820362, -0.016483020037412643, 0.029775291681289673, -0.007602604106068611, -0.014494473114609718, -0.024240626022219658, -0.006290767341852188, 0.014176909811794758, -0.003056541783735156, -0.04324902594089508, 0.000268888717982918, 0.013677882961928844, 0.019220110028982162, 0.007496749982237816, -0.019477182999253273, 0.028610894456505775, 0.04947930574417114, 0.014675936661660671, 0.004041364416480064, 0.037926070392131805, -0.007024186197668314, -0.02662990801036358, -0.020747434347867966, -0.008173461072146893, 0.022168906405568123, -0.009693225845694542, -0.010509815998375416, 0.0003397732798475772, -0.015469844453036785, 0.05419738218188286, 0.023514768108725548, 0.017768394201993942, 0.02042987197637558, -0.003924168646335602, 0.007576140575110912, 0.030848955735564232, -0.017768394201993942, -0.024558188393712044, -0.025707462802529335, -0.035748496651649475, -0.01858498342335224, -0.035627517849206924, -0.01701229251921177, -0.06593208014965057, 0.011764944531023502, -0.0027068445924669504, 0.009156393818557262, 0.04004315286874771, 0.020565969869494438, -0.007107357494533062, -0.01174982264637947, -0.038742657750844955, -0.0498422347009182, 0.02127670682966709, -0.050961267203092575, 0.05068906769156456, 0.021805977448821068, -0.0010075056925415993, 0.01525813527405262, -0.012883976101875305, 0.011719578877091408, 0.011764944531023502, 0.04482171684503555, 0.01258909609168768, -0.036867525428533554, -0.030198708176612854, 0.013821542263031006, 0.005534665659070015, -0.022804033011198044, -0.007088454905897379, 0.013919834978878498, 0.006218937691301107, 0.029941633343696594, -0.0554676316678524, 0.015484966337680817, -0.026040147989988327, -0.020505482330918312, -0.008309559896588326, 0.025495754554867744, -0.051566146314144135, -0.026100635528564453, 0.0323006696999073, 0.003931729588657618, -0.04076901078224182, -0.018358152359724045, 0.027960646897554398, -0.022894764319062233, 0.007296382915228605, 0.005905155558139086, -0.0032228841446340084, -0.01841864176094532, -0.047543685883283615, 0.009352980181574821, 0.04285585507750511, 0.008990051224827766, 0.025238679721951485, -0.02008206583559513, 0.004820149391889572, -0.007239675149321556, 0.007999558001756668, 0.02777918241918087, -0.006536500528454781, 0.00033528392668813467, -0.04055730253458023, 0.0007012845017015934, 0.01612009108066559, 0.0066650379449129105, -0.014562522061169147, -0.001597265130840242, -0.03753289580345154, 0.032633356750011444, 0.005311615765094757, 0.009126149117946625, -0.037926070392131805, 0.041222672909498215, 0.020187919959425926, 0.030153341591358185, 0.01267226692289114, 0.006385280285030603, -0.01876644790172577, 0.036655817180871964, 0.02517819218337536, 0.020278651267290115, -0.013685443438589573, 0.026040147989988327, 0.008801025338470936, -0.04321878403425217, -0.026947470381855965, -0.01339812483638525, 0.012702511623501778, -0.012793243862688541, 0.05679837241768837, -0.009095905348658562, -0.022501591593027115, -0.006910771131515503, -0.008445657789707184, -0.0200064554810524, 0.02499672770500183, 0.005701008252799511, -0.018146444112062454, 0.002540502231568098, -0.01628643460571766, 0.047029536217451096, 5.853882248629816e-05, 0.04524513706564903, -0.0012589095858857036, -0.003094346961006522, -0.03777484968304634, -0.0058106426149606705, -0.02812698855996132, 0.0045063672587275505, 0.02747674100100994, -0.040708523243665695, -0.02564697526395321, 0.009322735480964184, 0.022425981238484383, 0.016225945204496384, 0.016422532498836517, -0.004294658545404673, -0.011175185441970825, -0.027461620047688484, -0.014887645840644836, 0.004154779948294163, 0.01713326759636402, -0.008944684639573097, -0.032330915331840515, 0.0332382395863533, 0.007538335397839546, -0.012324460782110691, -0.030319685116410255, 0.015462283045053482, -0.02080792374908924, -0.019628403708338737, -0.006937234662473202, 0.005844667553901672, -0.005360762123018503, -0.01504642702639103, 0.04182755574584007, 0.04551733285188675, 0.00010408214438939467, -0.03269384428858757, -0.016724973917007446, -0.015500088222324848, -0.020021576434373856, -0.034175805747509, 0.003358982503414154, -0.022894764319062233, -0.05413689464330673, 0.009194198995828629, 0.008521268144249916, -0.04179731011390686, 0.0063399141654372215, -0.016301555559039116, -0.004396732430905104, -0.018070833757519722, 0.0089522460475564, -0.016573753207921982, -0.019764503464102745, 0.019809868186712265, 0.012022019363939762, 0.023741599172353745, 0.001742814783938229, 0.0188420582562685, 0.014925451017916203, 0.0027049544733017683, -0.010865183547139168, -0.047422707080841064, -0.019734257832169533, -0.013950079679489136, -0.0402548648416996, -0.006502476055175066, -0.004018681589514017, 0.022335248067975044, 0.0367465503513813, -0.022289883345365524, 0.0027068445924669504, -0.013254465535283089, 0.016437655314803123, -0.03716996684670448, 0.011840554885566235, -0.01523545291274786, 0.013511540368199348, -0.004415635019540787, 0.001920498674735427, 0.003194530261680484, -0.044942695647478104, -0.005942960735410452, 0.0013817761791869998, -0.001612387248314917, 0.029805535450577736, -0.016770338639616966, 0.03166554495692253, -0.006101741921156645, 0.019084010273218155, 0.010577864944934845, 0.013284709304571152, 0.02440696768462658, -0.01358715072274208, 0.0027030641213059425, 0.006638574413955212, 0.03735143318772316, -0.012581534683704376, 0.041525114327669144, 0.0035177639219909906, 0.002353366930037737, -0.036686062812805176, -0.02239573746919632, 0.00781809352338314, -0.023045985028147697, 0.005179297644644976, -0.03260311111807823, 0.004132096655666828, -0.018479129299521446, -0.006615891121327877, 0.018690837547183037, -0.03296604007482529, 0.0034137999173253775, 0.007931508123874664, 0.019386451691389084, -0.038863636553287506, -0.006241620983928442, -0.016271311789751053, -0.007795410230755806, -0.018010346218943596, 0.014963256195187569, 0.04206950590014458, -0.006846502423286438, -0.04182755574584007, 0.017768394201993942, 0.004589538089931011, -0.001226775231771171, -0.010434205643832684, 0.041736822575330734, 0.017072780057787895, -0.012014458887279034, -0.037926070392131805, -0.008876635693013668, 0.026766005903482437, -0.007916386239230633, 0.008672487922012806, 0.0054666162468492985, 0.043702688068151474, -0.01940157450735569, 0.002149219624698162, -0.021942075341939926, -0.057554472237825394, 0.010933232493698597, -0.014365935698151588, 0.0035877032205462456, 0.01305787917226553, 0.004287097603082657, -0.008929562754929066, -0.04896515607833862, -0.04013388603925705, 0.03384311869740486, 0.018736204132437706, -0.020399628207087517, 0.009708347730338573, 0.020112309604883194, -0.0098293237388134, 0.004631123971194029, -0.0033325189724564552, -0.019885478541254997, -0.01098616048693657, 0.01769278384745121, 0.05235249176621437, -0.008082728832960129, -0.03520410135388374, -0.03115139715373516, -0.017798637971282005, -0.0027843450661748648, -0.012279094196856022, 0.004827710334211588, -0.02136743813753128, 0.040406081825494766, -0.0008983435109257698, 0.014781791716814041, -0.02499672770500183, -0.014154226519167423, 0.023998672142624855, -0.01453227736055851, -0.014426423236727715, 0.0489046685397625, 0.011840554885566235, -0.022078175097703934, 0.010592986829578876, -0.035960204899311066, -0.015114475972950459, -0.018176687881350517, -0.01633179932832718, -0.013367881067097187, 0.035627517849206924, 0.016694728285074234, -0.0009389839833602309, 0.02321232669055462, -0.01466081477701664, -0.007700897287577391, 0.013413246721029282, 0.015288379974663258, 0.03726070001721382, 0.02688698284327984, 0.01271763350814581, -0.004003559239208698, -0.010517376475036144, 0.03550654277205467, 0.03565776348114014, -0.03850070759654045, 0.0023930624593049288, -0.012513485737144947, -0.027703572064638138, 0.025495754554867744, 0.010706402361392975, 0.000559515377972275, -0.022456225007772446, -0.01661911979317665, -0.024890873581171036, -0.016951803117990494, 0.017632296308875084, 0.021427927538752556, -0.014260080642998219, -0.0003952995175495744, -0.003710569813847542, 0.0008595932740718126, -0.0226981770247221, 0.012142996303737164, 0.014743986539542675, -0.02157914638519287, 0.022531835362315178, 0.010033471509814262, 0.016891315579414368, -0.012271532788872719, -0.010464449413120747, 0.007802971173077822, 0.007277480326592922, 0.0005996832624077797, 0.015560576692223549, -0.004672709386795759, 0.004495025612413883, 0.014925451017916203, 0.00886907521635294, -0.01640740968286991, -0.037593383342027664, 0.014766668900847435, -0.007224553264677525, 0.04896515607833862, 0.012256410904228687, -0.0014110751217231154, 0.03217969462275505, 0.018600106239318848, 0.0226981770247221, -0.01042664423584938, -0.04439830034971237, -0.007421139627695084, 0.012324460782110691, -0.001315617235377431, 0.009715909138321877, -0.04624319076538086, 0.04823929816484451, -0.0038258754648268223, 0.0014176910044625401, 0.032421648502349854, 0.009625176899135113, -0.012679828330874443, 0.0098293237388134, 0.01406349427998066, -0.009844446554780006, -0.03363141044974327, 0.029155287891626358, -0.025994781404733658, -0.023832330480217934, -0.026312345638871193, 0.02218402922153473, 0.010517376475036144, 0.0064344266429543495, 0.03964998200535774, 0.013624955900013447, 0.010804696008563042, 0.009685664437711239, 0.0035253248643130064, -0.0013042757054790854, -0.03278457745909691, -0.0003752155462279916, 0.026735762134194374, 0.0010821707546710968, -0.02564697526395321, -0.002047145739197731, 0.048571985214948654, -0.0012324460549280047, 0.008937124162912369, 0.010381278581917286, -0.005277590826153755, -0.012324460782110691, -0.004846612922847271, -0.01773815043270588, -0.006290767341852188, -0.015878139063715935, -0.029986999928951263, -0.025783073157072067, 0.019794747233390808, 0.006343694403767586, -0.011515431106090546, -0.002521599642932415, 0.021337194368243217, 0.007848337292671204, -0.0020811704453080893, -0.0008898373926058412, -0.0054855188354849815, 0.02602502517402172, 0.04064803570508957, 0.009262247942388058, 0.010910550132393837, 0.012944463640451431, 0.02153378166258335, -0.017919614911079407, -0.01893279142677784, -0.0013761053560301661, 0.012294216081500053, 0.018690837547183037, -0.024225503206253052, -0.005402348004281521, -0.010948355309665203, -0.005319176707416773, -0.037079233676195145, 0.03236116096377373, 0.005572470836341381, -0.027809426188468933, -0.026297222822904587, 0.0048806373961269855, -0.03320799395442009, 0.011500309221446514, 0.026040147989988327, 0.03538556769490242, 0.016936682164669037, 0.00942102912813425, 0.025495754554867744, 0.025329412892460823, -0.015605942346155643, 0.018615227192640305, 0.001165341935120523, -0.0043400246649980545, 0.031907498836517334, 0.01760205067694187, -0.031090907752513885, 0.004309780430048704, 0.01360983308404684, 0.01661911979317665, -0.029155287891626358, 0.027234788984060287, -0.005856008734554052, -0.0088917575776577, -0.0006181132630445063, -0.0008099740953184664, 0.005394786596298218, -0.01785912550985813, 0.0027881255373358727, -0.014985938556492329, 0.01432056911289692, 0.00814321730285883, 0.0061433278024196625, 0.03701874613761902, -0.0160293597728014, 0.0035877032205462456, -0.011311284266412258, 0.03644410893321037, 0.00778784928843379, 0.03901485726237297, -0.016770338639616966, -0.01909913308918476, -0.03559727594256401, 0.011961531825363636, -0.0033003846183419228, -0.011976653710007668, -0.006101741921156645, -0.01584789529442787, 0.0013108915882185102, 0.005874911323189735, -0.013987884856760502, 0.020490359514951706, 0.003464836860075593, -0.006290767341852188, -0.02752210758626461, 0.001937511027790606, -0.023061105981469154, 0.004260634072124958, 0.007670653518289328, 0.024890873581171036, 0.032633356750011444, -0.0016426312504336238, -0.012664706446230412, 0.017919614911079407, -0.0465758740901947, -0.015742041170597076, -0.047755394130945206, 0.002712515415623784, 0.029246019199490547, -0.029593827202916145, 0.0100637162104249, 0.021609392017126083, 0.010282984934747219, 0.030803589150309563, -0.01147762592881918, 0.011212990619242191, -0.003557459218427539, 0.039680223912000656, 0.00995786115527153, -0.02824796549975872, 0.006838941480964422, -0.011386893689632416, 0.009927617385983467, -0.005602714605629444, 0.006131986156105995, -0.009526883251965046, 0.02029377408325672, -0.042462680488824844, -0.03710947930812836, -0.01914449967443943, 0.033359214663505554, -0.011137380264699459, 0.02684161625802517, 0.022849397733807564, -0.004211487248539925, -0.0012787572341039777, -0.010736646130681038, -0.014827157370746136, -0.04285585507750511, 0.004120755009353161, 0.018947912380099297, 0.022667933255434036, 0.039045099169015884, -0.012483241967856884, -0.01572691835463047, 0.03281481936573982, 0.0013515320606529713, -0.012528607621788979, -0.008120534010231495, 0.011137380264699459, 0.0023741598706692457, -0.0070582106709480286, -0.008407852612435818, 0.009799079969525337, 0.0032569088507443666, -0.006305889692157507, -0.007893703877925873, -0.0015405575977638364, 0.008922002278268337, -0.016437655314803123, -0.023303059861063957, -0.019673770293593407, -0.00029204433667473495, -0.02124646306037903, 0.007421139627695084, -0.03145383670926094, 0.025163069367408752, 0.0027673328295350075, -0.007462725508958101, 0.014010567218065262, 0.04191828891634941, 0.006290767341852188, -0.03308701887726784, 0.004317341838032007, -0.006313450634479523, 0.003247457556426525, 0.023257693275809288, -0.03856119513511658, 0.019552793353796005, 0.05038662627339363, -0.030138220638036728, -0.00339678768068552, -0.024709409102797508, 0.02085328847169876, 0.04249292612075806, -0.01850937306880951, -0.0006970313843339682, -0.011681773699820042, -0.022622568532824516, -0.010676158592104912, -0.001289153704419732, 0.12139971554279327, -0.03680703788995743, -0.029593827202916145, 0.017874248325824738, 0.036050938069820404, 0.002090621739625931, -0.014774230308830738, 0.004449659492820501, 0.001894980319775641, -0.0039052660576999187, -0.006691501475870609, -0.034296780824661255, -0.03889387845993042, -0.019840111956000328, -0.0044534397311508656, 0.03961973637342453, -0.005530884955078363, -0.03266359865665436, -0.009481517598032951, -0.017768394201993942, 0.01636204496026039, -0.04261390119791031, -0.0017598271369934082, 0.0036273987498134375, -0.002950687427073717, -0.025964537635445595, -0.025677219033241272, -0.009640298783779144, 0.0038863634690642357, 0.058703746646642685, 0.019416695460677147, 0.0026784909423440695, 0.015787407755851746, 0.008853952400386333, -0.004657587502151728, 0.0307733453810215, -0.030440660193562508, -0.02936699613928795, -0.031211884692311287, 0.005383445415645838, -0.03756314143538475, -0.0004727999330498278, 0.03151432424783707, -0.02017279714345932, -0.0024403186980634928, -0.005685885902494192, 0.014554960653185844, 0.0007390895625576377, 0.005243566352874041, -0.00933785829693079, -0.01755668595433235, 0.044640254229307175, -0.004438317846506834, 0.011235673911869526, 0.009073222056031227, 0.001162506639957428, 0.015061548911035061, 0.02487575076520443, 0.05580031871795654, -7.63190328143537e-05, -0.0024630017578601837, -0.009058100171387196, 0.028731871396303177, 0.022244516760110855, 0.001828821375966072, -0.013791297562420368, -0.013042757287621498, 0.02431623637676239, -0.02829333208501339, 0.03047090582549572, 0.00392038794234395, 0.011802749708294868, 0.016135213896632195, 0.026781128719449043, 0.02948797307908535, 0.0348714180290699, -0.047210998833179474, -0.002757881535217166, -0.02316696010529995, 0.0050923461094498634, 0.002062267856672406, -0.014373496174812317, 0.012082507833838463, 0.023983551189303398, 0.02466404251754284, 0.01100884284824133, 0.011212990619242191, 0.02026353031396866, -0.026312345638871193, -0.01271763350814581, 0.006094180978834629, 6.645426765317097e-05, 0.006381499581038952, -0.02157914638519287, 0.006706623360514641, 0.013299832120537758, -0.04424707964062691, 0.017707904800772667, 0.006479792762547731, 0.005277590826153755, 0.023923063650727272, 0.013352759182453156, 0.009156393818557262, 0.02346940152347088, -0.004018681589514017, -0.019930845126509666, 0.0009645024547353387, -0.03538556769490242, -0.04182755574584007, 0.012422753497958183, -0.003122700611129403, -0.012793243862688541, 0.002992273075506091, 0.015288379974663258, 0.020611336454749107, -0.06859356164932251, -0.03629288822412491, -0.015348867513239384, -0.0022361711598932743, 0.0013468064134940505, 0.04572904109954834, 0.023711353540420532, -0.00011867254943354055, -0.023393791168928146, 0.041948530822992325, -0.016694728285074234, 0.047120269387960434, 0.01610497012734413, 0.04397488385438919, -0.023741599172353745, 0.011583480052649975, -0.014025689102709293, 0.021185973659157753, 0.01053249929100275, -0.005753935314714909, 0.012090068310499191, 0.01820693351328373, -0.02859577164053917, 0.012558852322399616, 0.014055933803319931, 0.013050317764282227, -0.03157481551170349, -0.001053816988132894, -0.01346617378294468, -0.0014536058297380805, 0.015432039275765419, 0.0498422347009182, 0.013375441543757915, -0.018312787637114525, -0.042371947318315506, -0.03133286163210869, -0.018736204132437706, 0.0025575144682079554, -0.02653917483985424, -0.00237226951867342, 0.006623452063649893, -0.035234346985816956, -0.011311284266412258, 0.004245511721819639, -0.018327908590435982, -0.0188420582562685, -0.009352980181574821, 0.01047201082110405, -0.008732976391911507, -0.01581765152513981, 0.00680491654202342, -0.029079677537083626, 0.002519709523767233, -0.03251238167285919, -0.0069258930161595345, 0.048874422907829285, -0.041555359959602356, -0.01226397231221199, 0.03747240826487541, 0.039680223912000656, -0.014139104634523392, 0.00762906763702631, 0.008218827657401562, 0.02321232669055462, 0.005081004463136196, -0.049509551376104355, -0.04333975911140442, 0.026690395548939705, -0.02162451297044754, -0.016558630391955376, 0.026569418609142303, -0.027537230402231216, -0.0011738481698557734, -0.0003797048993874341, -0.044851962476968765, 0.007175406441092491, -0.015621064230799675, -0.0024384285788983107, -0.006865405011922121, -0.022123539820313454, -0.028217721730470657, -0.032754331827163696, -0.049086131155490875, -0.0024837946984916925, -0.009247126057744026, -0.024165015667676926, -0.03565776348114014, 0.0061622303910553455, 0.01260421797633171, -0.0001532287715235725, 0.011341528035700321, -0.016679607331752777, 0.0100032277405262, -0.015953749418258667, -0.01098616048693657, 0.01940157450735569, 0.018403518944978714, -0.018600106239318848, -0.001313726999796927, 0.050114430487155914, 0.06069985777139664, 0.010971037670969963, 0.008581755682826042, 0.009005173109471798, -0.0017683332553133368, -0.004200145602226257, -0.007723580580204725, 0.028429429978132248, -0.011757384054362774, -0.018055712804198265, 0.02368110977113247, 0.002863735891878605, -0.027234788984060287, -0.019053766503930092, -0.007077113259583712, 0.04467049613595009, 0.02064158022403717, 0.012513485737144947, 0.02855040691792965, -0.011402016505599022, 0.01106933131814003, -0.0069447956047952175, 0.005481738597154617, 0.0014829047722741961, -0.007553457748144865, -0.0044874646700918674, -0.030879199504852295, 0.0007438152097165585, -0.0074022370390594006, -0.012437875382602215, 0.017329854890704155, 0.04715051129460335, -0.020717190578579903, 0.018025469034910202, 0.005326737649738789, 0.007470286451280117, 0.03753289580345154, -0.017934735864400864, -0.012029580771923065, -0.002107633976265788, -0.005447714123874903, 0.012762999162077904, 0.0029204434249550104, 0.02466404251754284, -0.005572470836341381, -0.0298357792198658, -0.0037748385220766068, 0.01586301624774933, -0.02244110405445099, 0.012967146933078766, -0.01940157450735569, 0.021805977448821068, 0.023786963894963264, 0.01264958456158638, 0.02042987197637558, -0.00344593427143991, -0.009239564649760723, 0.01654350943863392, -0.011825433000922203, -0.01846400834619999, 0.03224018216133118, 0.020248407498002052, -0.013299832120537758, 0.013677882961928844, -0.011885921470820904, -0.02372647635638714, -0.031090907752513885, -0.013640077784657478, -0.004884418100118637, -0.015469844453036785, -0.011228112503886223, 0.009065661579370499, 0.006150888744741678, -0.023832330480217934, 0.008249071426689625, 0.060881320387125015, -0.00021537089196499437, 0.002865626011043787, 0.008196144364774227, 0.006449548993259668, 0.0241045281291008, -0.005776618141680956, 0.034085072576999664, 0.031121153384447098, -0.008218827657401562, -0.023136716336011887, -0.00037946863449178636, 0.02405916154384613, -0.022501591593027115, -0.010207375511527061, 0.013246904127299786, 0.028414307162165642, 0.0009399291011504829, -0.008377608843147755, -0.022168906405568123, -0.005538445897400379, 0.018705960363149643, 0.0017579367849975824, -0.008559073321521282, 0.0006058266153559089, 0.008725415915250778, -0.018524495884776115, 0.021851344034075737, -0.021911831572651863, 0.04016413167119026, 0.03381287679076195, 0.011061769910156727, 0.006011009681969881, 0.020203040912747383, -0.006525158882141113, -0.0320587195456028, 0.008551511913537979, -0.024694286286830902, 0.020157676190137863, -0.030062610283493996, 0.019250353798270226, 0.001834492082707584, 0.0577964261174202, -0.028837725520133972, 0.02295525185763836, -0.009647860191762447, -0.011175185441970825, -0.008702732622623444, 0.025011848658323288, -0.023514768108725548, 0.013534223660826683, 0.020157676190137863, -0.008687610737979412, 0.02675088308751583, 0.013662761077284813, 0.007647970225661993, 0.025783073157072067, -0.016558630391955376, -0.016603996977210045, 0.015295940451323986, -0.023650866001844406, 0.00995786115527153, 0.009700787253677845, -0.020626459270715714, -0.04829978570342064, 0.010895428247749805, -0.008044923655688763, -0.011908603832125664, -0.0036009352188557386, -0.03366165608167648, -0.03992217779159546, -0.01504642702639103, -0.026690395548939705, -0.009511761367321014, -0.02637283317744732, 0.050023697316646576, -0.039982665330171585, 0.00023344645160250366, 0.010078838095068932, -0.008959807455539703, 0.003515873569995165, -0.0017352537252008915, 0.027416253462433815, -0.029518216848373413, 0.002502697054296732, -0.019462062045931816, 0.010093959979712963, -0.024437211453914642, 0.028474796563386917, 0.010585426352918148, -0.002803247654810548, -0.02991138957440853, 0.006298328284174204, -0.006479792762547731, 0.009708347730338573, 0.01331495400518179, -0.019643526524305344, -0.019371328875422478, -0.022471347823739052], {'text': 'hello world'})]\n" - ] - } - ], - "source": [ - "sym_text = Symbol(\"hello world\")\n", - "zip_result = sym_text.zip()\n", - "print(f\"Zip result: {zip_result}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 19. Input/Output Handling Operations\n", - "\n", - "### File Operations (`open`)" - ] - }, - { - "cell_type": "code", - "execution_count": 63, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "File contents: Hello from SymbolicAI file operations!\n", - "File contents from path symbol: Hello from SymbolicAI file operations!\n" - ] - } - ], - "source": [ - "# Create a sample file for demonstration\n", - "import tempfile\n", - "import os\n", - "\n", - "# Create a temporary file\n", - "with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as f:\n", - " f.write(\"Hello from SymbolicAI file operations!\")\n", - " temp_file_path = f.name\n", - "\n", - "# Open file with path parameter\n", - "sym_empty = Symbol()\n", - "opened_result = sym_empty.open(temp_file_path)\n", - "print(f\"File contents: {opened_result}\")\n", - "\n", - "# Open file with path as Symbol value\n", - "sym_path = Symbol(temp_file_path)\n", - "opened_from_value = sym_path.open()\n", - "print(f\"File contents from path symbol: {opened_from_value}\")\n", - "\n", - "# Cleanup\n", - "os.unlink(temp_file_path)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 20. Persistence Operations\n", - "\n", - "### Saving and Loading Symbols (`save`, `load`)" - ] - }, - { - "cell_type": "code", - "execution_count": 64, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Saved to text: /var/folders/fq/xwdrwyn112ndt59wfq_5m3mr0000gn/T/tmppncyyog9.txt\n", - "Saved to pickle: /var/folders/fq/xwdrwyn112ndt59wfq_5m3mr0000gn/T/tmpra8v8crk.pkl\n", - "Loaded from pickle: Hello, persistence test!\n" - ] - } - ], - "source": [ - "import tempfile\n", - "import os\n", - "\n", - "sym_test = Symbol(\"Hello, persistence test!\")\n", - "\n", - "# Create temporary files for demonstration\n", - "with tempfile.NamedTemporaryFile(delete=False, suffix='.pkl') as f:\n", - " pickle_path = f.name\n", - "\n", - "with tempfile.NamedTemporaryFile(delete=False, suffix='.txt') as f:\n", - " text_path = f.name\n", - "\n", - "# Save as text\n", - "sym_test.save(text_path, serialize=False, replace=True)\n", - "print(f\"Saved to text: {text_path}\")\n", - "\n", - "# Save as pickle (serialized)\n", - "sym_test.save(pickle_path, serialize=True, replace=True)\n", - "print(f\"Saved to pickle: {pickle_path}\")\n", - "loaded_sym = Symbol().load(pickle_path)\n", - "print(f\"Loaded from pickle: {loaded_sym}\")\n", - "\n", - "# Cleanup\n", - "os.unlink(pickle_path)\n", - "os.unlink(text_path)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Dynamic Function Expansion (`expand`)" - ] - }, - { - "cell_type": "code", - "execution_count": 65, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Generated function name: _llm_fibonacci_sequence_\n", - "Function attached to symbol: True\n" - ] - } - ], - "source": [ - "sym_task = Symbol(\"Calculate the fibonacci sequence up to 10 numbers\")\n", - "func_name = sym_task.expand()\n", - "print(f\"Generated function name: {func_name}\")\n", - "print(f\"Function attached to symbol: {hasattr(sym_task, func_name)}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 21. Output Processing Operations\n", - "\n", - "### Output Handling (`output`)" - ] - }, - { - "cell_type": "code", - "execution_count": 66, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Basic output:\n", - " {'result': 'None', 'processed': \"symbol_value: 'Hello, output test!'\\nsymbol_kwargs: {'static_context': ''}\", 'args': '[]', 'kwargs': '{}'}\n", - "Custom handler output:\n", - " {'result': 'None', 'processed': \"symbol_value: 'Hello, output test!'\\nsymbol_kwargs: {'static_context': ''}\\nmethod_kwargs: {'handler': }\", 'args': '[]', 'kwargs': '{}'}\n", - "Output with args:\n", - " {'result': 'None', 'processed': \"symbol_value: 'Hello, output test!'\\nsymbol_kwargs: {'static_context': ''}\\nmethod_args: ('arg1', 'arg2')\\nmethod_kwargs: {'custom_param': 'value'}\", 'args': '[]', 'kwargs': '{}'}\n" - ] - } - ], - "source": [ - "sym_test = Symbol(\"Hello, output test!\")\n", - "\n", - "# Basic output processing\n", - "result = sym_test.output()\n", - "print(f\"Basic output:\\n {result}\")\n", - "\n", - "# Custom handler function\n", - "def custom_handler(input_dict):\n", - " return f\"Custom processed: {input_dict}\"\n", - "\n", - "result_with_handler = sym_test.output(handler=custom_handler)\n", - "print(f\"Custom handler output:\\n {result_with_handler}\")\n", - "\n", - "# With additional arguments\n", - "result_with_args = sym_test.output(\"arg1\", \"arg2\", custom_param=\"value\")\n", - "print(f\"Output with args:\\n {result_with_args}\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.12.9" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/symbolicai-main/symbolicai-main/icon_converter.py b/symbolicai-main/symbolicai-main/icon_converter.py deleted file mode 100644 index 0ad9a6bd5da5040c60db739ed2af1af63e028982..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/icon_converter.py +++ /dev/null @@ -1,221 +0,0 @@ -import os -import platform -import shutil -import cairosvg -from PIL import Image - - -def create_ico(png_path, ico_path): - """Create a high-quality ICO file with multiple sizes.""" - # Define the sizes we want to include - sizes = [(16, 16), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)] - - # Open original PNG - img = Image.open(png_path) - - # Create a list to store all the images - img_list = [] - - # Create each size with high quality - for size in sizes: - resized_img = img.copy() - resized_img.thumbnail(size, Image.Resampling.LANCZOS) - # Convert to RGBA if not already - if resized_img.mode != 'RGBA': - resized_img = resized_img.convert('RGBA') - img_list.append(resized_img) - - # Save as ICO with multiple sizes - img_list[0].save( - ico_path, - format='ICO', - sizes=[(img.width, img.height) for img in img_list], - append_images=img_list[1:] - ) - - -def create_icns(png_path, icns_path): - """Create an ICNS file for macOS.""" - if not os.path.exists('iconset'): - os.makedirs('iconset') - - # Define the required sizes for ICNS - icon_sizes = { - (16, 16): "16x16", - (32, 32): "32x32", - (64, 64): "64x64", - (128, 128): "128x128", - (256, 256): "256x256", - (512, 512): "512x512", - (1024, 1024): "1024x1024" - } - - img = Image.open(png_path) - - # Create each size - for size, name in icon_sizes.items(): - resized_img = img.copy() - resized_img.thumbnail(size, Image.Resampling.LANCZOS) - - # Convert to RGBA if not already - if resized_img.mode != 'RGBA': - resized_img = resized_img.convert('RGBA') - - # Save normal and @2x versions - resized_img.save(f'iconset/icon_{name}.png') - if size[0] <= 512: # Don't create @2x for 1024 - resized_img.save(f'iconset/icon_{name}@2x.png') - - # Use iconutil to create icns (macOS only) - if os.path.exists('iconset'): - os.system(f'iconutil -c icns iconset -o {icns_path}') - # Clean up - import shutil - shutil.rmtree('iconset') - - -def create_favicon(svg_path, output_path): - """Create a high-quality favicon.ico with optimal sizes.""" - # Favicon-specific sizes (common favicon sizes) - favicon_sizes = [96, 144, 192] - temp_pngs = [] - images = [] - - try: - for size in favicon_sizes: - temp_png = f'temp_favicon_{size}.png' - # Convert SVG to PNG with higher quality settings - cairosvg.svg2png( - url=svg_path, - write_to=temp_png, - output_width=size, - output_height=size, - scale=2.0 # Increase internal resolution for better quality - ) - - # Open and optimize the PNG - img = Image.open(temp_png) - - # Ensure RGBA mode - if img.mode != 'RGBA': - img = img.convert('RGBA') - - # Apply minimal smoothing - img = img.resize((size, size), Image.Resampling.LANCZOS) - - images.append(img.copy()) - temp_pngs.append(temp_png) - img.close() - - # Save as ICO with all sizes - images[0].save( - output_path, - format='ICO', - sizes=[(size, size) for size in favicon_sizes], - append_images=images[1:], - optimize=True - ) - - finally: - # Clean up temporary files - for temp_png in temp_pngs: - if os.path.exists(temp_png): - os.remove(temp_png) - - -def convert_svg_to_ico(svg_path, output_path, sizes=[16, 32, 48, 64, 128, 256]): - """Convert SVG to ICO with multiple sizes.""" - # Create temporary PNG files for each size - temp_pngs = [] - images = [] - - try: - for size in sizes: - temp_png = f'temp_{size}.png' - # Convert SVG to PNG - cairosvg.svg2png( - url=svg_path, - write_to=temp_png, - output_width=size, - output_height=size - ) - # Open PNG and append to images list - img = Image.open(temp_png) - images.append(img.copy()) - temp_pngs.append(temp_png) - img.close() - - # Save as ICO - images[0].save( - output_path, - format='ICO', - sizes=[(size, size) for size in sizes], - append_images=images[1:] - ) - - finally: - # Clean up temporary files - for temp_png in temp_pngs: - if os.path.exists(temp_png): - os.remove(temp_png) - - -def convert_svg_to_icns(svg_path, output_path): - """Convert SVG to ICNS for macOS.""" - sizes = [16, 32, 64, 128, 256, 512, 1024] - temp_pngs = [] - iconset_path = 'icon.iconset' - - try: - # Create iconset directory - if not os.path.exists(iconset_path): - os.makedirs(iconset_path) - - # Generate PNG files at different sizes - for size in sizes: - temp_png = f'{iconset_path}/icon_{size}x{size}.png' - temp_png2x = f'{iconset_path}/icon_{size//2}x{size//2}@2x.png' - - # Convert SVG to PNG - cairosvg.svg2png( - url=svg_path, - write_to=temp_png, - output_width=size, - output_height=size - ) - - # Also save as @2x version if applicable - if size > 16: - os.rename(temp_png, temp_png2x) - - temp_pngs.append(temp_png) - - # Use iconutil to create icns (macOS only) - os.system(f'iconutil -c icns {iconset_path} -o {output_path}') - - finally: - # Clean up - if os.path.exists(iconset_path): - shutil.rmtree(iconset_path) - - -def main(svg_path='public/eai.svg'): - try: - import cairosvg - except ImportError: - os.system('pip install cairosvg pillow') - import cairosvg - - # Convert for Windows - convert_svg_to_ico(svg_path, 'icon.ico', sizes=[128]) - - # Create favicon - create_favicon(svg_path, 'favicon.ico') - - # Convert for macOS (only on macOS systems) - if platform.system() == 'Darwin': - convert_svg_to_icns(svg_path, 'icon.icns') - - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/installer.py b/symbolicai-main/symbolicai-main/installer.py deleted file mode 100644 index 0e33b3f20b7eeeaf9446266f46f2b7d021710846..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/installer.py +++ /dev/null @@ -1,333 +0,0 @@ -import os -import platform -import queue -import customtkinter -import threading -import subprocess -from customtkinter import CTkButton, CTkEntry, CTk, CTkProgressBar, CTkLabel, CTkTextbox - - -def get_anaconda_url(): - # Check if anaconda is already installed - if platform.system() == 'Windows': - if os.path.exists(os.path.expanduser('~\\Anaconda3')): - return None - else: - if os.path.exists(os.path.expanduser('~/anaconda3')): - return None - - # Get Anaconda download URL based on OS - system = platform.system() - if system == 'Linux': - return 'https://repo.anaconda.com/archive/Anaconda3-2023.09-0-Linux-x86_64.sh' - elif system == 'Windows': - return 'https://repo.anaconda.com/archive/Anaconda3-2024.10-1-Windows-x86_64.exe' - elif system == 'Darwin': - # distinguish between Apple Silicon and Intel Macs - if 'arm' in platform.processor(): - return 'https://repo.anaconda.com/archive/Anaconda3-2024.10-1-MacOSX-arm64.sh' - else: - return 'https://repo.anaconda.com/archive/Anaconda3-2024.10-1-MacOSX-x86_64.sh' - - -def run_command(command): - process = subprocess.Popen( - command, - shell=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - universal_newlines=True, - bufsize=1 - ) - - output = [] - # Read output and error streams line by line - while True: - line = process.stdout.readline() - error = process.stderr.readline() - - if not line and not error and process.poll() is not None: - break - - if line: - output.append(('stdout', line.strip())) - if error: - output.append(('stderr', error.strip())) - - returncode = process.wait() - return returncode, output - - -class InstallerGUI: - def __init__(self): - customtkinter.set_appearance_mode("System") - customtkinter.set_default_color_theme("blue") - - self.root = CTk() - self.root.geometry("800x700") # Increased window size - self.root.title("SymbolicAI Installer") - - self.is_installing = False - self.log_queue = queue.Queue() - self.setup_gui() - - # Start the log consumer - self.root.after(100, self.process_log_queue) - - def setup_gui(self): - # Welcome Label - welcome_label = CTkLabel(self.root, text="Welcome to the SymbolicAI Installer!") - welcome_label.pack(pady=20) - - # API Key Entry - api_key_label = CTkLabel(self.root, text="Enter your API Key:") - api_key_label.pack(pady=5) - - self.api_key_entry = CTkEntry(self.root, width=300, placeholder_text="Your API Key here") - self.api_key_entry.pack(pady=10) - # Add validation for API key entry - self.api_key_entry.bind('', self.validate_api_key) - # Add focus out event - self.api_key_entry.bind('', lambda e: self.root.focus()) - - # Progress Components - self.log_text = CTkLabel(self.root, text="") - self.log_text.pack(pady=10) - - self.progress_bar = CTkProgressBar(self.root, width=300) - self.progress_bar.set(0) - self.progress_bar.pack(pady=10) - - # Output Text Box - self.output_text = CTkTextbox(self.root, width=700, height=300) - self.output_text.pack(pady=10, padx=20) - - # Install Button (modified to start as disabled) - self.install_button = CTkButton( - self.root, - text='Install Anaconda & SymbolicAI Package', - command=self.start_installation, - state="disabled" # Start with disabled button - ) - self.install_button.pack(pady=20) - - def log(self, message, message_type="info"): - self.log_queue.put((message, message_type)) - - def validate_api_key(self, event=None): - """Validate API key and enable/disable install button accordingly""" - api_key = self.api_key_entry.get().strip() - self.install_button.configure(state="normal" if api_key else "disabled") - - def process_log_queue(self): - try: - while True: - message, message_type = self.log_queue.get_nowait() - self.output_text.configure(state="normal") - - # Add color coding based on message type - if message_type == "error": - message = f"ERROR: {message}\n" - tag = "error" - elif message_type == "stderr": - message = f"STDERR: {message}\n" - tag = "error" - elif message_type == "stdout": - message = f"OUTPUT: {message}\n" - tag = "stdout" - else: - message = f"INFO: {message}\n" - tag = "info" - - self.output_text.insert("end", message) - self.output_text.see("end") - self.output_text.configure(state="disabled") - - except queue.Empty: - pass - finally: - self.root.after(100, self.process_log_queue) - - def update_gui(self, message, progress=None): - def update(): - self.log_text.configure(text=message) - if progress is not None: - self.progress_bar.set(progress) - self.root.after(0, update) - - def install_anaconda(self): - try: - self.update_gui('Installing Anaconda...', 0.2) - self.log("Starting Anaconda installation") - url = get_anaconda_url() - - if url is None: - self.log("Anaconda already installed") - self.update_gui('Anaconda already installed.', 0.4) - return True - - if platform.system() == 'Windows': - download_cmd = f'powershell -Command "Invoke-WebRequest -Uri {url} -OutFile anaconda_installer.exe"' - self.log(f"Downloading Anaconda with command: {download_cmd}") - returncode, output = run_command(download_cmd) - for stream, line in output: - self.log(line, stream) - if returncode != 0: - raise Exception("Failed to download Anaconda installer") - - install_cmd = 'start /wait "" anaconda_installer.exe /InstallationType=JustMe /RegisterPython=0 /S /D=%UserProfile%\\Anaconda3' - self.log(f"Installing Anaconda with command: {install_cmd}") - returncode, output = run_command(install_cmd) - for stream, line in output: - self.log(line, stream) - if returncode != 0: - raise Exception("Failed to install Anaconda") - else: - self.log(f"Downloading Anaconda from: {url}") - returncode, output = run_command(f'curl -LO {url}') - for stream, line in output: - self.log(line, stream) - if returncode != 0: - raise Exception("Failed to download Anaconda installer") - - file_name = url.split('/')[-1] - self.log(f"Installing Anaconda with file: {file_name}") - returncode, output = run_command(f'bash {file_name} -b') - for stream, line in output: - self.log(line, stream) - if returncode != 0: - raise Exception("Failed to install Anaconda") - - self.update_gui('Anaconda installed.', 0.4) - return True - except Exception as e: - self.log(str(e), "error") - self.update_gui(f'Error installing Anaconda: {str(e)}') - return False - - def create_environment(self): - try: - self.update_gui('Creating environment...', 0.6) - self.log("Creating conda environment") - - if platform.system() == 'Windows': - conda_path = os.path.expanduser('~\\Anaconda3\\Scripts\\conda.exe') - else: - conda_path = os.path.expanduser('~/anaconda3/bin/conda') - - if not os.path.exists(conda_path): - raise Exception("Conda not found. Please ensure Anaconda is installed correctly.") - - cmd = f'"{conda_path}" create -y --name symaiprod python=3.10' - self.log(f"Running command: {cmd}") - returncode, output = run_command(cmd) - for stream, line in output: - self.log(line, stream) - if returncode != 0: - raise Exception("Failed to create conda environment") - - self.update_gui('Environment created.', 0.7) - return True - except Exception as e: - self.log(str(e), "error") - self.update_gui(f'Error creating environment: {str(e)}') - return False - - def install_symbolicai(self): - try: - self.update_gui('Installing SymbolicAI...', 0.8) - self.log("Installing SymbolicAI package") - - if platform.system() == 'Windows': - conda_path = os.path.expanduser('~\\Anaconda3\\Scripts\\conda.exe') - activate_cmd = f'"{conda_path}" activate symaiprod' - pip_install_cmd = 'pip install symbolicai' - full_cmd = f'{activate_cmd} && {pip_install_cmd}' - else: - # For macOS and Linux - conda_path = os.path.expanduser('~/anaconda3/bin/conda') - # Use the full path to pip in the conda environment - pip_path = os.path.expanduser('~/anaconda3/envs/symaiprod/bin/pip') - full_cmd = f'"{pip_path}" install symbolicai' - - self.log(f"Running command: {full_cmd}") - returncode, output = run_command(full_cmd) - for stream, line in output: - self.log(line, stream) - if returncode != 0: - raise Exception("Failed to install SymbolicAI") - - self.update_gui('SymbolicAI installed.', 0.9) - return True - except Exception as e: - self.log(str(e), "error") - self.update_gui(f'Error installing SymbolicAI: {str(e)}') - return False - - def installation_process(self): - try: - api_key = self.api_key_entry.get().strip() - self.update_gui('Starting installation...', 0.1) - - if self.install_anaconda(): - if self.create_environment(): - if self.install_symbolicai(): - # Set API Key - os.environ['NEUROSYMBOLIC_ENGINE_API_KEY'] = api_key - - # Test Installation using the correct Python path - self.update_gui('Testing installation...', 0.9) - - # Use the correct Python path based on the OS - if platform.system() == 'Windows': - python_path = os.path.expanduser('~\\Anaconda3\\envs\\symaiprod\\python.exe') - test_cmd = f'"{python_path}" -c "from symai import *"' - else: - python_path = os.path.expanduser('~/anaconda3/envs/symaiprod/bin/python') - test_cmd = f'"{python_path}" -c "from symai import *"' - - self.log(f"Testing installation with command: {test_cmd}") - returncode, output = run_command(test_cmd) - - if returncode == 0: - self.update_gui('Installation completed successfully!', 1.0) - else: - error_message = "\n".join([line[1] for line in output if line[0] == 'stderr']) - self.update_gui(f'Error testing installation: {error_message}') - - self.is_installing = False - self.install_button.configure(state="normal") - - except Exception as e: - self.log(str(e), "error") - self.update_gui(f'Installation failed: {str(e)}') - self.is_installing = False - self.install_button.configure(state="normal") - - def start_installation(self): - if self.is_installing: - return - - api_key = self.api_key_entry.get().strip() - if not api_key: - self.update_gui("Please enter a valid API key!") - return - - self.is_installing = True - self.install_button.configure(state="disabled") - self.progress_bar.set(0) - - # Start installation in a separate thread - threading.Thread(target=self.installation_process, daemon=True).start() - - def run(self): - self.root.mainloop() - - -def main(): - installer = InstallerGUI() - installer.run() - - -if __name__ == '__main__': - main() diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/Basics.ipynb b/symbolicai-main/symbolicai-main/legacy/notebooks/Basics.ipynb deleted file mode 100644 index 7ccb09a273745192832fa1f0bcffc33220193d00..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/Basics.ipynb +++ /dev/null @@ -1,782 +0,0 @@ -{ - "cells": [ - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# SymbolicAI: Basics" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Get Imports" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [], - "source": [ - "import os\n", - "import warnings\n", - "warnings.filterwarnings('ignore')\n", - "os.chdir('../') # set the working directory to the root of the project\n", - "import numpy as np\n", - "from symai import *\n", - "from symai.components import *\n", - "from IPython.display import display" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Using Symbols" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "Hi there!" - ], - "text/plain": [ - "(value=Hi there!)" - ] - }, - "execution_count": 2, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "sym = Symbol('Hi there!')\n", - "sym" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Adding two symbols together." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "Hi there! How are you?" - ], - "text/plain": [ - "(value=Hi there! How are you?)" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "res = sym + 'how are you?'\n", - "res" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If one of the objects is a symbol then the other object is converted to a symbol." - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "A `Symbol` instance takes in any type of object and preserves its original value type until it is evaluated and sent to the neuro-symbolic engine:" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "numpy.ndarray" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "sym = Symbol(np.array([5, 2, 42, 1]))\n", - "sym.value_type" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "One can also easily retriev the object by accessing the `value` attribute:" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "array([ 5, 2, 42, 1])" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "sym.value" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can add multiple values together and their operation will be contextualized evaluated. Here we use the shift operator to integrate a new value into the existing symbol:" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "['5', '2', '42', '1', '2']" - ], - "text/plain": [ - "(value=['5', '2', '42', '1', '2'])" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "res = sym << 2\n", - "res" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We could do the same manipulation with the `+` operator, however, the prompts designed for each individual operator may contain different information, therefore, therefore may not evaluated to similar outcomes. In the following example it is clear that the `+` operator is not to shift the value into the array:" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "[\"5\", \"2\", \"42\", \"3\"]" - ], - "text/plain": [ - "(value=[\"5\", \"2\", \"42\", \"3\"])" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "res = sym + 2\n", - "res" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "However, if we use the `+` operator to evaluate arithmetic operations, the results are quite different:" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "x + 1" - ], - "text/plain": [ - "(value=x + 1)" - ] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x = Symbol('x')\n", - "x += 1\n", - "x" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For simple expressions and operations we can use LLMs to interpret the mathematical expression and evaluate the result:" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "x + 1 = 0\n", - "\n", - "To solve for x:\n", - "\n", - "x + 1 - 1 = 0 - 1\n", - "\n", - "x = -1" - ], - "text/plain": [ - "(value=x + 1 = 0\n", - "\n", - "To solve for x:\n", - "\n", - "x + 1 - 1 = 0 - 1\n", - "\n", - "x = -1)" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x = Symbol('x + 1 = 0')\n", - "x.interpret()" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Evaluating Expressions" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Similar to `word2vec` we intend to preform contextualized operations on different symbols. \n", - "\n", - "Word2vec is a machine learning algorithm that is used to generate dense vector representations of words. It works by training a shallow neural network to predict a word given its neighbors in a text corpus. The resulting vectors are then used in a wide range of natural language processing applications, such as sentiment analysis, text classification, and clustering.\n", - "\n", - "Below we can see an example how one can perform operations on the word embedding vectors (colored boxes)." - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "However, we can also perform operations on the natural language space itself. For example, we can add two the word expressions similar to how we added them in the word2vec space:" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "Queen" - ], - "text/plain": [ - "(value=Queen)" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Symbol('King - Man + Women').interpret()" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As we can see, if the `expression` method is empty the default implementation of `Symbol` uses only the `value` stored within the current symbol. \n", - "\n", - "Now let's try to evaluate a more complex expression:" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - " x^2 + 2x + 1\n", - "
" - ], - "text/plain": [ - "(value=x^2 + 2x + 1)" - ] - }, - "execution_count": 2, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "expression = Interface('wolframalpha')\n", - "res = expression('x^2 + 2x + 1')\n", - "res\n" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Well, not exactly simplified the way we intended it. \n", - "\n", - "This is because using LLMs for expression evaluations is still very limited, therefore, to leverage the full power of symbolic programming we can use the `expression` method to evaluate an expression via `WolframAlpha`:" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - " x = -1\n", - "
" - ], - "text/plain": [ - "(value=x = -1)" - ] - }, - "execution_count": 12, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "sym = Symbol()\n", - "expression = Interface('wolframalpha')\n", - "res = expression('x^2 + 2x + 1')\n", - "res" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "There we go! The `command` method configures the `symbolic` engine to evaluate expressions via `WolframAlpha`. One can see that this evaluates the expression and returns the correct result." - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Showing other basic operations" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Sometimes we want to simply concatenate to symbols together without any other neural operation. This is easily done with the `|` operation:" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "Welcome to our tutorial.Hello world!" - ], - "text/plain": [ - "(value=Welcome to our tutorial.Hello world!)" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# define a second string\n", - "sym = Symbol(\"Welcome to our tutorial.\")\n", - "test2 = 'Hello world!'\n", - "# concatenate strings\n", - "res = sym | test2\n", - "res" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can of course define full sentences as Symbols and perform several operations on them." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "sym = Symbol(\"\"\"Images and videos of domestic cats make up some of the most viewed content on the World Wide Web, particularly image macros in the form of lolcats. ThoughtCatalog has described cats as the \"unofficial mascot of the Internet\".[1]\n", - "The subject has attracted the attention of various scholars and critics, who have analyzed why this form of low art has reached iconic status. Although it may be considered frivolous, cat-related Internet content contributes to how people interact with media and culture.[2] Some argue that there is a depth and complexity to this seemingly simple content, with a suggestion that the positive psychological effects that pets have on their owners also hold true for cat images viewed online.[3]\n", - "Research has suggested that viewing online cat media is related to positive emotions, and that it even may work as a form of digital therapy or stress relief for some users. Some elements of research also shows that feelings of guilt when postponing tasks can be reduced by viewing cat content.[4]\n", - "\"\"\")" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here we translate the existing Symbol to German:" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "Bilder und Videos von Hauskatzen gehören zu den am meisten gesehenen Inhalten im World Wide Web, insbesondere Bildmakros in Form von Lolcats. ThoughtCatalog hat Katzen als das \"inoffizielle Maskottchen des Internets\" beschrieben.[1]\n", - "Das Thema hat die Aufmerksamkeit verschiedener Gelehrter und Kritiker auf sich gezogen, die analysiert haben, warum diese Form der niedrigen Kunst einen ikonischen Status erreicht hat. Obwohl es als belanglos angesehen werden kann, trägt internetbezogener Katzeninhalt dazu bei, wie Menschen mit Medien und Kultur interagieren.[2] Einige argumentieren, dass es eine Tiefe und Komplexität in diesem scheinbar einfachen Inhalt gibt, mit dem Vorschlag, dass die positiven psychologischen Effekte, die Haustiere auf ihre Besitzer haben, auch für online betrachtete Katzenbilder zutreffen.[3]\n", - "Die Forschung hat vorgeschlagen, dass das Anschauen von Katzenmedien im Internet mit positiven Emotionen verbunden ist und dass es sogar als eine Form der digitalen Therapie oder Stressentlastung für einige Nutzer dienen kann. Einige Forschungsergebnisse zeigen auch, dass Gefühle der Schuld, wenn Aufgaben aufgeschoben werden, durch das Betrachten von Katzeninhalten reduziert werden können.[4]" - ], - "text/plain": [ - "(value=Bilder und Videos von Hauskatzen gehören zu den am meisten gesehenen Inhalten im World Wide Web, insbesondere Bildmakros in Form von Lolcats. ThoughtCatalog hat Katzen als das \"inoffizielle Maskottchen des Internets\" beschrieben.[1]\n", - "Das Thema hat die Aufmerksamkeit verschiedener Gelehrter und Kritiker auf sich gezogen, die analysiert haben, warum diese Form der niedrigen Kunst einen ikonischen Status erreicht hat. Obwohl es als belanglos angesehen werden kann, trägt internetbezogener Katzeninhalt dazu bei, wie Menschen mit Medien und Kultur interagieren.[2] Einige argumentieren, dass es eine Tiefe und Komplexität in diesem scheinbar einfachen Inhalt gibt, mit dem Vorschlag, dass die positiven psychologischen Effekte, die Haustiere auf ihre Besitzer haben, auch für online betrachtete Katzenbilder zutreffen.[3]\n", - "Die Forschung hat vorgeschlagen, dass das Anschauen von Katzenmedien im Internet mit positiven Emotionen verbunden ist und dass es sogar als eine Form der digitalen Therapie oder Stressentlastung für einige Nutzer dienen kann. Einige Forschungsergebnisse zeigen auch, dass Gefühle der Schuld, wenn Aufgaben aufgeschoben werden, durch das Betrachten von Katzeninhalten reduziert werden können.[4])" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "sym.translate('German')" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And now, we try to classify how the mood of the above sentences:" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "neutral" - ], - "text/plain": [ - "(value=neutral)" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "sym.choice(['angry', 'neutral', 'hate-speech', 'happy', 'unk'], default='unk')" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Documentation Generator Example" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "from examples.docs import Docs, CppDocs\n", - "docs = Docs()" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\"\"\"Decorates a function to be executed with pre_processors, post_processors, and constraints.\n", - "\n", - "This decorator is used to apply preprocessing, postprocessing, and constraint validation to the output of a function. It provides a way to hook into the execution of the function, allowing for additional processing or validation steps to be applied before and after the function runs.\n", - "\n", - "Args:\n", - " default (str, optional): The default value to be returned if the validation of constraints fails. It can also be used to provide a default response if the function cannot be executed. Defaults to None.\n", - " constraints (List[Callable], optional): A list of callables that are used to validate the output of the function. An empty list means no constraints will be applied. Defaults to an empty list ( [] ).\n", - " pre_processors (List[PreProcessor], optional): A list of preprocessing objects that are applied to the arguments of the function before the function is called. Preprocessors can modify or augment the function arguments. Defaults to an empty list ( [] ).\n", - " post_processors (List[PostProcessor], optional): A list of postprocessing objects that are applied to the output of the function after the function has completed execution. Postprocessors can modify or filter the function's output. Defaults to an empty list ( [] ).\n", - " **decorator_kwargs: Additional keyword arguments that are passed to the execute_func function.\n", - "\n", - "Returns:\n", - " Callable: A wrapper function that, when called, executes the wrapped function with preprocessing, postprocessing, and constraint checks applied.\n", - "\n", - "Example Usage:\n", - " @execute(default='Error', constraints=[check_positive], post_processors=[format_result])\n", - " def calculate_area(length, width):\n", - " return length * width\n", - "\n", - " class MathOperations:\n", - " @execute(pre_processors=[convert_to_int])\n", - " def multiply(self, a, b):\n", - " return a * b\n", - "\"\"\"\n" - ] - } - ], - "source": [ - "doc = docs(\"\"\"def execute(default: str = None,\n", - " constraints: List[Callable] = [],\n", - " pre_processors: List[PreProcessor] = [],\n", - " post_processors: List[PostProcessor] = [],\n", - " **decorator_kwargs):\n", - " def decorator(func):\n", - " @functools.wraps(func)\n", - " def wrapper(instance, *args, **kwargs):\n", - " return execute_func(instance,\n", - " func=func,\n", - " constraints=constraints,\n", - " default=default,\n", - " pre_processors=pre_processors,\n", - " post_processors=post_processors,\n", - " **decorator_kwargs)\n", - " return wrapper\n", - " return decorator\n", - "\"\"\")\n", - "print(doc)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Markdown" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can actually on the fly also generate markdown documentation for our notebooks. This is done by using the built in `query` method. The `query` method is used to query the `symbolic` engine for information about the current symbol. The `query` method can therefore be used to ask the engine to generate documentation in a specific format." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "```markdown\n", - "# News Class Documentation\n", - "\n", - "The `News` class is a utility that helps developers inject uniform preprocessing, postprocessing, and constraint validation behaviors into their methods. It's implemented as a Python decorator, which can be easily applied to any function.\n", - "\n", - "## Overview\n", - "\n", - "The `News` class decorator streamlines the process of enhancing functions with additional processing layers. It allows functions to be wrapped such that:\n", - "\n", - "- Input arguments can be pre-processed before the function runs.\n", - "- Output can be post-processed after the function completes.\n", - "- The output can be validated against constraints to ensure it adheres to certain requirements.\n", - "\n", - "By using this decorator, developers can maintain cleaner codebases by separating concerns and avoiding repetitive code.\n", - "\n", - "## Features\n", - "\n", - "### Pre-Processing\n", - "\n", - "Pre-processors are used to transform or prepare the input data before the core logic of the function is executed. They can be used, for example, to validate input types, convert formats, or enrich data.\n", - "\n", - "### Post-Processing\n", - "\n", - "Post-processors are applied after the function has produced an output. They can be used for formatting the output, performing additional calculations on the results, or logging.\n", - "\n", - "### Constraints\n", - "\n", - "Constraints serve as checks or validations applied to the function's output. They can raise exceptions or alter the output if it does not meet pre-determined criteria.\n", - "\n", - "## Syntax and Arguments\n", - "\n", - "When decorating a function with the `News` class, you can provide several optional arguments:\n", - "\n", - "- `default`: The default value to return if constraints validation fails, or if the function cannot be executed.\n", - "- `constraints`: A list of callables that receive the function's output and return a boolean value indicating whether the output meets the constraint.\n", - "- `pre_processors`: Objects that are called with the function's arguments before the function itself is called.\n", - "- `post_processors`: Objects that are called with the function's output after it has executed.\n", - "- `**decorator_kwargs`: Any additional keyword arguments that should be passed to the `execute_func` function.\n", - "\n", - "The decorator returns a callable that represents the wrapped function.\n", - "\n", - "## Example Usage\n", - "\n", - "```python\n", - "@execute(default='Error', constraints=[check_positive], post_processors=[format_result])\n", - "def calculate_area(length, width):\n", - " return length * width\n", - "\n", - "class MathOperations:\n", - " @execute(pre_processors=[convert_to_int])\n", - " def multiply(self, a, b):\n", - " return a * b\n", - "```\n", - "\n", - "In the example above, the `calculate_area` function is decorated to return the string `'Error'` by default if any of the constraints fail. It also applies a post-processor that formats the final result.\n", - "\n", - "For the `MathOperations` class, the `multiply` method is decorated with a pre-processor that ensures the inputs are converted to integers before the multiplication occurs.\n", - "\n", - "## Conclusion\n", - "\n", - "The `News` class decorator offers a versatile and powerful way to enhance functions with additional processing and validation. It promotes cleaner, more modular code and helps ensure that functions operate within defined parameters.\n", - "```\n" - ] - } - ], - "source": [ - "res = doc.query(context=\"Write a very detailed Markdown documentation the News class.\")\n", - "print(res)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "continualrl", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.13" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "7f6e76e437f50039fcb1dabeb26a40fb80edddddd3448a5d408bb52a844f2e97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/ChatBot.ipynb b/symbolicai-main/symbolicai-main/legacy/notebooks/ChatBot.ipynb deleted file mode 100644 index e084990e803b8b1653c4a2668bbee1c2d34c1281..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/ChatBot.ipynb +++ /dev/null @@ -1,179 +0,0 @@ -{ - "cells": [ - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# ChatBot" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Get Imports" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import os\n", - "import warnings\n", - "warnings.filterwarnings('ignore')\n", - "os.chdir('../') # set the working directory to the root of the project\n", - "from symai import *\n", - "from symai.components import *\n", - "from IPython.display import display" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Writing a chatbot is *fairly* easy with our framework. All we need to do is basically derive from the `ChatBot` class and implement the `forward` method. The base class `ChatBot` has already some helper capabilities and context detection dictionaries. All we have to do is use the `self.narrate` method to instruct our chatbot to say what we want. \n", - "\n", - "Afterwards, we can use the `self.context_choice` method to classify the context of the user input. This is done by using a dictionary of context keywords. The `self.context_choice` method returns the context key that matches the user input. This key can then be used to determine the next action / condition of the chatbot.\n", - "\n", - "See the following example:" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By creating an instance of the `SymbiaChat` and calling the `forward` method, we can start a chat with our chatbot. The `forward` method takes a user input and returns a chatbot response." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```python\n", - "from symai.chat import ChatBot\n", - "from symai.interfaces import Interface\n", - "\n", - "\n", - "class SymbiaChat(ChatBot):\n", - " def forward(self) -> str:\n", - " message = self.narrate('Symbia introduces herself, writes a greeting message and asks how to help.')\n", - " while True:\n", - " # query user\n", - " usr = self.input(message)\n", - "\n", - " # detect context\n", - " ctxt = self.context_choice(usr)\n", - "\n", - " if 'option 3' in ctxt: # exit\n", - " self.narrate('Symbia writes goodbye message.', end=True)\n", - " break # end chat\n", - "\n", - " elif 'option 4' in ctxt: # help\n", - " message = self.narrate('Symbia writes for each capability one sentence.',\n", - " context=self.capabilities)\n", - "\n", - " elif 'option 1' in ctxt: # chit chat\n", - " message = self.narrate('Symbia replies to the user question in a casual way.')\n", - "\n", - " elif 'option 2' in ctxt:\n", - " # detect command\n", - " option = self.capabilities_choice(usr)\n", - "\n", - " if 'option 1' in option:\n", - " q = usr.extract('user query request')\n", - " rsp = self.search(q)\n", - " message = self.narrate('Symbia replies to the user based on the online search results.',\n", - " context=rsp)\n", - " elif 'option 2' in option:\n", - " q = usr.extract('URL')\n", - " site = self.crawler(q)\n", - " site.save('tmp.html')\n", - " message = self.narrate('Symbia explains that the website is downloaded to the `tmp.html` file.')\n", - " elif 'option 3' in option:\n", - " pass\n", - "\n", - " # TODO ...\n", - "\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - " Symbia: Goodbye! If you have any more questions in the future, don't hesitate to reach out. Have a great day!\n" - ] - }, - { - "data": { - "text/html": [ - "Symbia: Goodbye! If you have any more questions in the future, don't hesitate to reach out. Have a great day!" - ], - "text/plain": [ - "(value=Symbia: Goodbye! If you have any more questions in the future, don't hesitate to reach out. Have a great day!)" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from symai.chat import SymbiaChat\n", - "\n", - "chat = SymbiaChat()\n", - "chat()" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The above bot can answer some trivia, use the Google search engine to retrieve information and " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "symai", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.13" - }, - "orig_nbformat": 4 - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/Conversation.ipynb b/symbolicai-main/symbolicai-main/legacy/notebooks/Conversation.ipynb deleted file mode 100644 index 704f3b2d12d199068e4667e6bd4dbd54bd72d39c..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/Conversation.ipynb +++ /dev/null @@ -1,229 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "from symai.components import FileReader, JsonParser" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "reader = FileReader()\n", - "code = reader('/Users/xpitfire/workspace/symbolicai/symai/constraints.py')" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [], - "source": [ - "parser = JsonParser(\"Extract all class methods:\", {'methods': [\n", - " {'name': 'command', 'params': ['params']},\n", - " {'name': 'forward', 'params': ['*args', '**kwargs']},\n", - "]})" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [], - "source": [ - "res = parser(code)" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "{'methods': [{'name': '__init__', 'params': ['format']}, {'name': '__call__', 'params': ['input']}, {'name': 'check_keys', 'params': ['json_format', 'gen_dict']}]}" - ], - "text/plain": [ - "(value={'methods': [{'name': '__init__', 'params': ['format']}, {'name': '__call__', 'params': ['input']}, {'name': 'check_keys', 'params': ['json_format', 'gen_dict']}]})" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "res" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "from symai.extended import FileMerger" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "merger = FileMerger()" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "Reading file: ...: 0it [00:00, ?it/s]\n" - ] - } - ], - "source": [ - "merged = merger('')" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [], - "text/plain": [ - "(value=)" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "merged" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Configuration file: /Users/xpitfire/.symai/symai.config.json\n", - "Module 'ExtensityAI/timezone' already installed.\n" - ] - } - ], - "source": [ - "# install symai package for timezone conversion\n", - "!sympkg i ExtensityAI/timezone" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "from symai import Conversation" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "conv = Conversation(file_link='/Users/xpitfire/.symai/packages/ExtensityAI/timezone/src/func.py')" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "The given Python code defines an `Expression` class called `Timezone`, which is a subclass of the `Expression` class (presumed to be part of the `symai` library, which is not a publicly documented library at the time of this writing). The `Timezone` class contains methods and data that allows it to handle time zone conversions based on a provided country code or time zone identifier. Here's a step-by-step explanation of the key elements in the code:\n", - "\n", - "1. **Imports and Constants**: The code imports necessary modules such as `symai`, `numpy` as `np`, and `SequenceMatcher` from `difflib`. `FUNCTION_DESCRIPTION` is a string literal describing the purpose of the function, which is to convert between time zones. Similarly, `COUNTRY_TIME_TABLE` provides a detailed table with country codes, corresponding time zones, offsets, and other related data.\n", - "\n", - "2. **Timezone Class**:\n", - " - The `Timezone` class inherits from `Expression`.\n", - " - A new instance of `Timezone` initializes a `Function` with `FUNCTION_DESCRIPTION`, which appears to describe what the function does (time zone conversions).\n", - " \n", - "3. **find_substring Method**:\n", - " - This method takes a country name string as its parameter. \n", - " - It splits the `COUNTRY_TIME_TABLE` string by newline characters, converting each line to lowercase.\n", - " - It then calculates the similarity ratios between the provided country name (converted to lowercase) and each time zone entry in the table using the `SequenceMatcher`.\n", - " - The method returns a dictionary where each key is a time zone entry, and each corresponding value is the similarity ratio.\n", - "\n", - "4. **forward Method**:\n", - " - This is the main method to calculate the result based on the user's request.\n", - " - The `request` parameter is converted to a `Symbol` to standardize the input.\n", - " - The `extract` method is called on the `request` to retrieve the country name for which the time zone conversion is needed.\n", - " - A `similarities` dictionary is created using the `find_substring` method, keyed by time zone entries with respective similarity ratios.\n", - " - It then gets the top 'k' similar time zones sorted in descending order based on their similarity ratios.\n", - " - A data string is constructed with the top 'k' time zones, and the original `request`.\n", - " - The method calls the `fn` function (which presumably performs the actual conversion operation) with this data and any additional arguments or keyword arguments.\n", - "\n", - "Given the code structure, it appears designed to work with a system for handling user requests (presumably related to time zone conversions), where the user's input (\"extract the target timezone or country\") would be received, processed, and used to find relevant time zones that closely match the user-provided country or time zone. The actual conversion logic, however, seems to be handled outside of this code snippet, within the `Function` object initialized with the `FUNCTION_DESCRIPTION` content.\n" - ] - } - ], - "source": [ - "conv('Explain the Expression');" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "symai", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.13" - }, - "orig_nbformat": 4 - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/Indexer.ipynb b/symbolicai-main/symbolicai-main/legacy/notebooks/Indexer.ipynb deleted file mode 100644 index 31ed48828487b0623b5fe10269fb1931cdb6d77d..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/Indexer.ipynb +++ /dev/null @@ -1,648 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "from symai.components import *\n", - "from symai.backend.mixin.tracker import OpenAICostTracker\n", - "from symai import *" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [], - "source": [ - "expr = Expression()" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [], - "source": [ - "class FuncDemo(Expression):\n", - " def forward(self, data: Symbol, **kwargs):\n", - " @core.query(context='Do some fancy decoration of sentences.')\n", - " def _func(_, data, **kwargs):\n", - " pass\n", - " return _func(self, data, **kwargs)" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [], - "source": [ - "leo_func = FuncDemo()" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "Data:\n", - "\n", - "Context: Do some fancy decoration of sentences.\n", - "Answer:" - ], - "text/plain": [ - "(value=Data:\n", - "\n", - "Context: Do some fancy decoration of sentences.\n", - "Answer:)" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "res = leo_func('Test', preview=True)\n", - "res" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "2023-11-30 22:15:07,833 ====== WebDriver manager ======\n", - "2023-11-30 22:15:07,833 ====== WebDriver manager ======\n", - "2023-11-30 22:15:07,833 ====== WebDriver manager ======\n", - "2023-11-30 22:15:07,833 ====== WebDriver manager ======\n", - "2023-11-30 22:15:08,121 Get LATEST chromedriver version for google-chrome\n", - "2023-11-30 22:15:08,121 Get LATEST chromedriver version for google-chrome\n", - "2023-11-30 22:15:08,121 Get LATEST chromedriver version for google-chrome\n", - "2023-11-30 22:15:08,121 Get LATEST chromedriver version for google-chrome\n", - "2023-11-30 22:15:08,183 Get LATEST chromedriver version for google-chrome\n", - "2023-11-30 22:15:08,183 Get LATEST chromedriver version for google-chrome\n", - "2023-11-30 22:15:08,183 Get LATEST chromedriver version for google-chrome\n", - "2023-11-30 22:15:08,183 Get LATEST chromedriver version for google-chrome\n", - "2023-11-30 22:15:08,229 Driver [/Users/xpitfire/.wdm/drivers/chromedriver/mac64/119.0.6045.105/chromedriver-mac-x64/chromedriver] found in cache\n", - "2023-11-30 22:15:08,229 Driver [/Users/xpitfire/.wdm/drivers/chromedriver/mac64/119.0.6045.105/chromedriver-mac-x64/chromedriver] found in cache\n", - "2023-11-30 22:15:08,229 Driver [/Users/xpitfire/.wdm/drivers/chromedriver/mac64/119.0.6045.105/chromedriver-mac-x64/chromedriver] found in cache\n", - "2023-11-30 22:15:08,229 Driver [/Users/xpitfire/.wdm/drivers/chromedriver/mac64/119.0.6045.105/chromedriver-mac-x64/chromedriver] found in cache\n" - ] - }, - { - "data": { - "text/plain": [ - "'Zum'" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "crawler = Interface('selenium') # load selenium interface\n", - "website = crawler('https://www.orf.at'); # load page\n", - "website.value[:100] # preview" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "from symai.extended import RepositoryCloner\n", - "cloner = RepositoryCloner() # load repository cloner" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Repository quam already exists. Checking for updates...\n", - "Repository quam is up-to-date.\n" - ] - }, - { - "data": { - "text/plain": [ - "'/Users/xpitfire/.symai/repos/quam'" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cloner('https://github.com/ml-jku/quam')" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "tracker = OpenAICostTracker() # load openai cost tracker\n", - "usage = TokenTracker() # load token tracker" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "with tracker: # track the cost using OpenAI API\n", - " conv = Conversation(file_link='/Users/xpitfire/workspace/symbolicai/symai/extended/repo_cloner.py') # create conversation" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Below is a Python class that includes a method to clone a repository from a given URL using the `git` command-line tool. The class makes use of the subprocess module to execute the `git clone` command. I have also included Python docstrings for documentation.\n", - "\n", - "```python\n", - "import subprocess\n", - "from typing import Optional\n", - "\n", - "class GitRepositoryCloner:\n", - " \"\"\"\n", - " A utility class to clone Git repositories using the `git` command-line tool.\n", - " \"\"\"\n", - " \n", - " @staticmethod\n", - " def clone_repository(repo_url: str, clone_directory: Optional[str] = None) -> bool:\n", - " \"\"\"\n", - " Clone a Git repository from the given URL into the specified directory.\n", - "\n", - " :param repo_url: The URL of the repository to clone.\n", - " :param clone_directory: Optional destination directory for the cloned repo.\n", - " If not provided, uses the default git behavior which\n", - " is to create a directory named after the repo under\n", - " the current working directory.\n", - " :return: True if the repository was successfully cloned, False otherwise.\n", - " \"\"\"\n", - " # Command composition\n", - " clone_command = [\"git\", \"clone\", repo_url]\n", - " if clone_directory:\n", - " clone_command.append(clone_directory)\n", - "\n", - " try:\n", - " # Execute the git clone command\n", - " subprocess.run(clone_command, check=True)\n", - " return True\n", - " except subprocess.CalledProcessError:\n", - " # The command failed\n", - " return False\n", - "\n", - "# Example Usage:\n", - "\n", - "# Assuming you want to clone the repository to the current working directory\n", - "# without specifying a directory name:\n", - "cloner = GitRepositoryCloner()\n", - "result = cloner.clone_repository(\"https://github.com/exampleuser/example-repo.git\")\n", - "print(\"Repository cloned successfully.\" if result else \"Failed to clone repository.\")\n", - "```\n", - "\n", - "This class defines a method `clone_repository` that takes a repository URL and an optional directory name as arguments. If cloning succeeds, it returns `True`; if it fails (e.g., because of an invalid repository URL, lack of internet connection, or insufficient permissions), it returns `False`. The subprocess `run` method executes the git command and raises a `CalledProcessError` if the git process exits with a non-zero status, which is caught and results in a return value of `False`.\n", - "\n", - "Please ensure that the environment where you execute this code has `git` installed and accessible from the command line. Also, remember that the `clone_directory` argument is optional. If not provided, git will clone the repository into a new directory with the same name as the repository under the current working directory.\n", - "\n", - "\n", - "================\n", - "[Used tokens: 0.00%]\n", - "================\n", - "\n", - "\n", - "\n", - "================\n", - "[Used tokens: 0.66%]\n", - "================\n", - "\n" - ] - } - ], - "source": [ - "with usage: # track the token usage how much we can converse without cutting off\n", - " conv(f\"Implement the code missing in the class to clone a repository based on an URL. Also write proper Python documentation.\") # query the conversation expression" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "The contents provided seem to suggest a request to retrieve data from a generator object, but no specific pseudo algorithm is available to base the Python code on. Generator objects in Python are created by functions that yield values instead of returning a final value.\n", - "\n", - "If you were asking to generate Python code from a pseudo algorithm to retrieve the next value from a generator object, the code could look something like this:\n", - "\n", - "```python\n", - "# Assuming 'gen_object' is the generator object that we need to retrieve values from\n", - "\n", - "# Create the generator object (for illustration purposes)\n", - "def sample_generator():\n", - " for i in range(3):\n", - " yield i\n", - "\n", - "# Replace the above 'sample_generator' with the actual generator creation logic\n", - "gen_object = sample_generator()\n", - "\n", - "# Retrieve the next value from the generator object\n", - "try:\n", - " next_value = next(gen_object)\n", - " print(f\"The next value from the generator object is: {next_value}\")\n", - "except StopIteration:\n", - " print(\"The generator has no more items.\")\n", - "```\n", - "\n", - "However, since the specific pseudo algorithm details are missing, I can't provide an exact translation to Python code. Please provide the pseudo algorithm you wish to convert into Python code.\n", - "\n", - "\n", - "================\n", - "[Used tokens: 0.00%]\n", - "================\n", - "\n", - "\n", - "\n", - "================\n", - "[Used tokens: 0.30%]\n", - "================\n", - "\n" - ] - } - ], - "source": [ - "from symai.components import TokenTracker, Stream\n", - "from symai.backend.mixin.tracker import OpenAICostTracker\n", - "from symai import *\n", - "website = 'wyour datddy' # load page\n", - "\n", - "with OpenAICostTracker() as tracker: # track the cost using OpenAI API\n", - " with Stream() as stream: # stream over the too long website content\n", - " fn = Function('Extract algorithm from website') # define function to operate on the stream\n", - " res = stream(website) # stream over the website content\n", - " conv = Conversation(init=res, file_link='/Users/xpitfire/create_new_a_star.py') # create conversation with file link\n", - " with TokenTracker() as usage: # track the token usage how much we can converse without cutting off\n", - " conv(f\"Generate from the pseudo algorithm corresponding python code:\") # query the conversation expression\n", - " conv.commit() # extract code and commit to the file" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "[BREAKDOWN]\n", - "-=--=--=--=--=--=--=--=--=--=--=--=--=-\n", - "\n", - "gpt-4-1106-preview usage:\n", - " $0.020 for 808 input tokens and 412 output tokens\n", - "\n", - "text-embedding-ada-002 usage:\n", - " $0.000 for 0 tokens\n", - "\n", - "Total:\n", - " $0.020\n", - "\n", - "-=--=--=--=--=--=--=--=--=--=--=--=--=-\n", - "\n", - "Zero-shot calls: 0\n", - "\n", - "-=--=--=--=--=--=--=--=--=--=--=--=--=-\n", - "\n", - "Few-shot calls: 2\n", - "\n", - "-=--=--=--=--=--=--=--=--=--=--=--=--=-\n", - "\n" - ] - } - ], - "source": [ - "print(tracker)" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "from symai.components import Indexer" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "indexer = Indexer()" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "2023-11-30 23:14:08,431 ====== WebDriver manager ======\n", - "2023-11-30 23:14:08,707 Get LATEST chromedriver version for google-chrome\n", - "2023-11-30 23:14:08,768 Get LATEST chromedriver version for google-chrome\n", - "2023-11-30 23:14:08,811 Driver [/Users/xpitfire/.wdm/drivers/chromedriver/mac64/119.0.6045.105/chromedriver-mac-x64/chromedriver] found in cache\n" - ] - } - ], - "source": [ - "from symai import Interface\n", - "res = Interface('selenium')('https://www.baidu-venture.net/touzizuhe.html')" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Using this website means that you agree to our use of cookies. We use cookies to provide you with a good experience and help our website operate effectively.'" - ] - }, - "execution_count": 2, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "res.value" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [], - "source": [ - "from symai import Symbol\n", - "from symai.components import Stream" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [], - "source": [ - "sym = Symbol(res) # convert to symbol" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [], - "source": [ - "sym.save('../outputs/tmp.html')" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "30" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "len(res)" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": {}, - "outputs": [], - "source": [ - "with Stream(retrieval='all') as stream:\n", - " fn = Function('Give a list of all investors')\n", - " inv = stream(res)" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[(value=It seems there is a misunderstanding. \"Baiduventure\" is not a recognized term, nor does it appear to be an investor or investment firm. If you are referring to Baidu Ventures (BV), this is the venture capital arm of Baidu, which is a leading Chinese internet services company. Baidu Ventures focuses on investing in early-stage startups in the AI, AR/VR, and IoT (Internet of Things) sectors among others.\n", - " \n", - " If you're requesting a list of all investors in general, that's an incredibly broad and nearly impossible task as there are countless investors worldwide. They range from individual angel investors, venture capitalists, and private equity firms to banks, pension funds, sovereign wealth funds, and corporations.\n", - " \n", - " If you're seeking a list of investors in a specific company, sector, or for a particular type of investment (like startups, real estate, etc.), please provide more details so that I could offer a more targeted list or information according to the knowledge cutoff date.)]" - ] - }, - "execution_count": 18, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "inv" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "from symai.components import *" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [], - "source": [ - "res = Interface('serpapi')('Who is the investor of PyTorch?')" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'query_displayed': 'Who is the investor of PyTorch?',\n", - " 'total_results': 378000,\n", - " 'time_taken_displayed': 0.86,\n", - " 'menu_items': [{'position': 1,\n", - " 'title': 'Images',\n", - " 'link': 'https://www.google.com/search?sca_esv=f4dbf1826554685d&q=Who+is+the+investor+of+PyTorch%3F&tbm=isch&source=lnms&sa=X&ved=2ahUKEwiw2fbd3-yCAxWsSjABHRMJAmUQ0pQJegQIDBAB',\n", - " 'serpapi_link': 'https://serpapi.com/search.json?device=desktop&engine=google_images&gl=us&google_domain=google.com&hl=en&q=Who+is+the+investor+of+PyTorch%3F'},\n", - " {'position': 2,\n", - " 'title': 'In python',\n", - " 'link': 'https://www.google.com/search?sca_esv=f4dbf1826554685d&q=Who+is+the+investor+of+pytorch+in+python&uds=H4sIAAAAAAAA_-OK4OL0zFMoqCzJyM8Tkg_PyFfILFYoyUhVyMwrSy0uyS9SyE9TCKgMyS9KzrA3ECrSwKEEaAJICVAMapgRIcMAp7Sn33sAAAA&sa=X&ved=2ahUKEwiw2fbd3-yCAxWsSjABHRMJAmUQxKsJegQICBAB&ictx=0',\n", - " 'serpapi_link': 'https://serpapi.com/search.json?device=desktop&engine=google&google_domain=google.com&q=Who+is+the+investor+of+pytorch+in+python'},\n", - " {'position': 3,\n", - " 'title': 'News',\n", - " 'link': 'https://www.google.com/search?sca_esv=f4dbf1826554685d&q=Who+is+the+investor+of+PyTorch%3F&tbm=nws&source=lnms&sa=X&ved=2ahUKEwiw2fbd3-yCAxWsSjABHRMJAmUQ0pQJegQICxAB',\n", - " 'serpapi_link': 'https://serpapi.com/search.json?device=desktop&engine=google&google_domain=google.com&q=Who+is+the+investor+of+PyTorch%3F&tbm=nws'},\n", - " {'position': 4,\n", - " 'title': 'Videos',\n", - " 'link': 'https://www.google.com/search?sca_esv=f4dbf1826554685d&q=Who+is+the+investor+of+PyTorch%3F&tbm=vid&source=lnms&sa=X&ved=2ahUKEwiw2fbd3-yCAxWsSjABHRMJAmUQ0pQJegQIChAB',\n", - " 'serpapi_link': 'https://serpapi.com/search.json?device=desktop&engine=google_videos&gl=us&google_domain=google.com&hl=en&q=Who+is+the+investor+of+PyTorch%3F'},\n", - " {'position': 5,\n", - " 'title': 'Shopping',\n", - " 'link': 'https://www.google.com/search?sca_esv=f4dbf1826554685d&q=Who+is+the+investor+of+PyTorch%3F&tbm=shop&source=lnms&sa=X&ved=2ahUKEwiw2fbd3-yCAxWsSjABHRMJAmUQ0pQJegQISBAB',\n", - " 'serpapi_link': 'https://serpapi.com/search.json?device=desktop&engine=google_shopping&gl=us&google_domain=google.com&hl=en&q=Who+is+the+investor+of+PyTorch%3F'},\n", - " {'position': 6,\n", - " 'title': 'Books',\n", - " 'link': 'https://www.google.com/search?sca_esv=f4dbf1826554685d&q=Who+is+the+investor+of+PyTorch%3F&tbm=bks&source=lnms&sa=X&ved=2ahUKEwiw2fbd3-yCAxWsSjABHRMJAmUQ0pQJegQISxAB'},\n", - " {'position': 7,\n", - " 'title': 'Maps',\n", - " 'link': 'https://maps.google.com/maps?sca_esv=f4dbf1826554685d&output=search&q=Who+is+the+investor+of+PyTorch?&source=lnms&entry=mc&sa=X&ved=2ahUKEwiw2fbd3-yCAxWsSjABHRMJAmUQ0pQJegQISRAB'},\n", - " {'position': 8,\n", - " 'title': 'Flights',\n", - " 'link': 'https://www.google.com/travel/flights?sca_esv=f4dbf1826554685d&output=search&q=Who+is+the+investor+of+PyTorch%3F&source=lnms&sa=X&ved=2ahUKEwiw2fbd3-yCAxWsSjABHRMJAmUQ0pQJegQIShAB'},\n", - " {'position': 9,\n", - " 'title': 'Finance',\n", - " 'link': 'https://www.google.com/finance?sca_esv=f4dbf1826554685d&output=search&q=Who+is+the+investor+of+PyTorch%3F&source=lnms&sa=X&ved=2ahUKEwiw2fbd3-yCAxWsSjABHRMJAmUQ0pQJegQITBAB'}],\n", - " 'organic_results_state': 'Results for exact spelling'}" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "res.raw['search_information']" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "from symai.extended import DocumentRetriever" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "docret = DocumentRetriever(file='')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "res = docret.query('What is the Theory of Mind paper about?')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "res" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "image = res.extract('main idea')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "symai310", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.13" - }, - "orig_nbformat": 4 - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/News.ipynb b/symbolicai-main/symbolicai-main/legacy/notebooks/News.ipynb deleted file mode 100644 index 5098f94431886c8fe6d4b6a1373e693ca7b85fc1..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/News.ipynb +++ /dev/null @@ -1,336 +0,0 @@ -{ - "cells": [ - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# SymbolicAI: Basics" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Get Imports" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import os\n", - "import warnings\n", - "warnings.filterwarnings('ignore')\n", - "os.chdir('../') # set the working directory to the root of the project\n", - "from symai import *\n", - "from symai.components import *\n", - "from IPython.display import display" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Handling large / long context lengths" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can create contextual prompts to define the semantic operations for our model. However, this takes away a lot of our context size and since the GPT-3 context length is limited to 4097 tokens, this might quickly become a problem. Luckily we can use the `Stream` processing expression. This expression opens up a data stream and computes the remaining context length for processing the input data. Then it chunks the sequence and computes the result for each chunk. The chunks can be processed with a `Sequence` expression, that allows multiple chained operations in a sequential manner.\n", - "\n", - "In the following example we show how we can extract news from a particular website and try to recombine all individual chunks again by clustering the information among the chunks and then recombining them. This gives us a way to consolidate contextually related information and recombine them in a meaningful way. Furthermore, the clustered information can then be labeled by looking / streaming through the values within the cluster and collecting the most relevant labels." - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If we repeat this process, we now get a way of building up a hierarchical cluster with labels as entry points to allow information retrieval from our new data structure." - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To make manners more concrete, lets take a look at how to build up a news generator. Let us first start by importing some pre-defined string constants. These constants are used to define how the text is processed and how we desire the output to be formatted." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "from examples.news import HEADER_STYLE_DESCRIPTION, HTML_TEMPLATE, HTML_STREAM_STYLE_DESCRIPTION" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### News Generator" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We sub-class the `Expression` class and define the `__init__` implementation. Similar to PyTorch we can define the graph in the `__init__` method and then call the `forward` method to compute the result. Afterwards, the data from the web URL is streamed through a `Sequence` of operations. This cleans the text from all the clutter such as `\\n`, `\\t`, etc. and then extracts the news from the text. \n", - "The news are then filtered and re-composed. The resulting news texts are then clustered and the clusters are labeled. The labeled clusters are then recombined to return a rendered HTML format." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [], - "source": [ - "class News(Expression):\n", - " \"\"\"The `News` class sub-classes `Expression` and provides a way to fetch and render news from a given url. It uses a `Stream` object to process the news data, with a sequence of `Clean`, `Translate`, `Outline`, and `Compose` expressions.\n", - " It also defines a `Style` for the header, and a `Symbol` for the HTML templates.\n", - " \"\"\"\n", - " def __init__(self, url: str, pattern: str, filters: List[Expression] = [], render: bool = False, **kwargs):\n", - " \"\"\"The `News` class constructor requires three arguments - `url`, `pattern` and `filters`.\n", - " * `url` is a `str` containing the url to fetch the news from.\n", - " * `pattern` is a `str` containing the name of the search key to be found on the web page.\n", - " * `filters` is a `List[Expression]` containing any additional filters that should be applied to the news data.\n", - " It defaults to an empty list if not specified.\n", - " The `News` class also has an optional `render` argument which is a `bool` indicating whether the news should be rendered. It defaults to `False` if not specified.\n", - " \"\"\"\n", - " super().__init__(**kwargs)\n", - " self.url = url\n", - " self.pattern = pattern\n", - " self.render_ = render\n", - " self.crawler = Interface('selenium')\n", - " filters = filters if isinstance(filters, List) or isinstance(filters, tuple) else [filters]\n", - " self.data_stream = Stream(Sequence(\n", - " Clean(),\n", - " Translate(),\n", - " Outline(),\n", - " *filters,\n", - " Compose(f'Compose news paragraphs. Combine only facts that belong topic-wise together:\\n'),\n", - " ))\n", - " self.header_style = Style(description=HEADER_STYLE_DESCRIPTION,\n", - " libraries=['https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css',\n", - " 'https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js',\n", - " 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js'])\n", - "\n", - " self.html_template = Symbol(HTML_TEMPLATE)\n", - " self.html_template_seq = Template()\n", - " self.html_stream = Stream(\n", - " Sequence(\n", - " self.html_template_seq,\n", - " Style(description=HTML_STREAM_STYLE_DESCRIPTION)\n", - " )\n", - " )\n", - "\n", - " def render(self, sym: Symbol) -> Symbol:\n", - " \"\"\"The `render` method takes a `Symbol` as an argument and returns a `Symbol` containing the rendered news.\n", - " It first sets the `html_template_seq` property of the `html_stream` to the result of applying the `header_style` to the `html_template`.\n", - " It then iterates through the `data_stream` and collects the strings resulting from each expression.\n", - " These strings are combined into a single `Symbol` object which is then clustered.\n", - " Finally, the `render` method applies the `html_template` to the clustered `Symbol` and returns the result.\n", - " \"\"\"\n", - " tmp = self.header_style(self.html_template)\n", - " self.html_template_seq.template_ = str(tmp)\n", - " res = '\\n'.join([str(s) for s in self.html_stream(sym)])\n", - " res = Symbol(str(tmp).replace('{{placeholder}}', res))\n", - " return res\n", - "\n", - " def forward(self) -> Symbol:\n", - " \"\"\"The `forward` method is used to fetch and process the news data.\n", - " It first calls the `fetch` method with the `url` and `pattern` arguments.\n", - " It then iterates through the `data_stream` and collects the `Symbol` object resulting from each expression.\n", - " These `Symbol` objects are then combined into a single `Symbol` object which is then mapped.\n", - " If `render` is `False`, the mapped `Symbol` is returned. Otherwise, the `render` method is called with the `Symbol` and the resulting `Symbol` is returned.\n", - " \"\"\"\n", - " res = self.crawler(url=self.url, pattern=self.pattern)\n", - " vals = []\n", - " for news in self.data_stream(res):\n", - " vals.append(str(news))\n", - " res = Symbol(vals).cluster()\n", - " sym = res.map()\n", - " if not self.render_:\n", - " return sym\n", - " return self.render(sym)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here you can try the news generator:" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [], - "source": [ - "# crawling the website and creating an own website based on its facts\n", - "news = News(url='https://www.cnbc.com/cybersecurity/',\n", - " pattern='cnbc',\n", - " filters=ExcludeFilter('sentences about subscriptions, licensing, newsletter'),\n", - " render=True)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Since the generative process will evaluate multiple expression, we can use the `Trace` and `Log` classes to keep track of what is happening. " - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "2023-12-01 00:20:34,771 ====== WebDriver manager ======\n", - "2023-12-01 00:20:35,096 Get LATEST chromedriver version for google-chrome\n", - "2023-12-01 00:20:35,178 Get LATEST chromedriver version for google-chrome\n", - "2023-12-01 00:20:35,224 Get LATEST chromedriver version for google-chrome\n", - "2023-12-01 00:20:35,312 WebDriver version 119.0.6045.105 selected\n", - "2023-12-01 00:20:35,314 Modern chrome version https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/119.0.6045.105/mac-x64/chromedriver-mac-x64.zip\n", - "2023-12-01 00:20:35,314 About to download new driver from https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/119.0.6045.105/mac-x64/chromedriver-mac-x64.zip\n", - "2023-12-01 00:20:35,465 Driver downloading response is 200\n", - "2023-12-01 00:20:35,897 Get LATEST chromedriver version for google-chrome\n", - "2023-12-01 00:20:36,039 Driver has been saved in cache [/Users/xpitfire/.wdm/drivers/chromedriver/mac64/119.0.6045.105]\n" - ] - }, - { - "ename": "AttributeError", - "evalue": "'Symbol' object has no attribute 'map'", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", - "\u001b[1;32m/Users/xpitfire/workspace/symbolicai/notebooks/News.ipynb Cell 16\u001b[0m line \u001b[0;36m2\n\u001b[1;32m 1\u001b[0m expr \u001b[39m=\u001b[39m Log(Trace(news))\n\u001b[0;32m----> 2\u001b[0m res \u001b[39m=\u001b[39m expr()\n\u001b[1;32m 3\u001b[0m os\u001b[39m.\u001b[39mmakedirs(\u001b[39m'\u001b[39m\u001b[39mresults\u001b[39m\u001b[39m'\u001b[39m, exist_ok\u001b[39m=\u001b[39m\u001b[39mTrue\u001b[39;00m)\n\u001b[1;32m 4\u001b[0m path \u001b[39m=\u001b[39m os\u001b[39m.\u001b[39mpath\u001b[39m.\u001b[39mabspath(\u001b[39m'\u001b[39m\u001b[39mresults/news.html\u001b[39m\u001b[39m'\u001b[39m)\n", - "File \u001b[0;32m~/workspace/symbolicai/symai/symbol.py:941\u001b[0m, in \u001b[0;36mExpression.__call__\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 930\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39m__call__\u001b[39m(\u001b[39mself\u001b[39m, \u001b[39m*\u001b[39margs, \u001b[39m*\u001b[39m\u001b[39m*\u001b[39mkwargs) \u001b[39m-\u001b[39m\u001b[39m>\u001b[39m Any:\n\u001b[1;32m 931\u001b[0m \u001b[39m \u001b[39m\u001b[39m'''\u001b[39;00m\n\u001b[1;32m 932\u001b[0m \u001b[39m Evaluate the expression using the forward method and assign the result to the value attribute.\u001b[39;00m\n\u001b[1;32m 933\u001b[0m \n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 939\u001b[0m \u001b[39m Any: The result of the forward method.\u001b[39;00m\n\u001b[1;32m 940\u001b[0m \u001b[39m '''\u001b[39;00m\n\u001b[0;32m--> 941\u001b[0m \u001b[39mreturn\u001b[39;00m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mforward(\u001b[39m*\u001b[39;49margs, \u001b[39m*\u001b[39;49m\u001b[39m*\u001b[39;49mkwargs)\n", - "File \u001b[0;32m~/workspace/symbolicai/symai/components.py:198\u001b[0m, in \u001b[0;36mLog.forward\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 196\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mforward\u001b[39m(\u001b[39mself\u001b[39m, \u001b[39m*\u001b[39margs, \u001b[39m*\u001b[39m\u001b[39m*\u001b[39mkwargs) \u001b[39m-\u001b[39m\u001b[39m>\u001b[39m Expression:\n\u001b[1;32m 197\u001b[0m Expression\u001b[39m.\u001b[39mcommand(logging\u001b[39m=\u001b[39m\u001b[39mTrue\u001b[39;00m, engines\u001b[39m=\u001b[39m\u001b[39mself\u001b[39m\u001b[39m.\u001b[39mengines)\n\u001b[0;32m--> 198\u001b[0m res \u001b[39m=\u001b[39m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mexpr(\u001b[39m*\u001b[39;49margs, \u001b[39m*\u001b[39;49m\u001b[39m*\u001b[39;49mkwargs)\n\u001b[1;32m 199\u001b[0m Expression\u001b[39m.\u001b[39mcommand(logging\u001b[39m=\u001b[39m\u001b[39mFalse\u001b[39;00m, engines\u001b[39m=\u001b[39m\u001b[39mself\u001b[39m\u001b[39m.\u001b[39mengines)\n\u001b[1;32m 200\u001b[0m \u001b[39mreturn\u001b[39;00m res\n", - "File \u001b[0;32m~/workspace/symbolicai/symai/symbol.py:941\u001b[0m, in \u001b[0;36mExpression.__call__\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 930\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39m__call__\u001b[39m(\u001b[39mself\u001b[39m, \u001b[39m*\u001b[39margs, \u001b[39m*\u001b[39m\u001b[39m*\u001b[39mkwargs) \u001b[39m-\u001b[39m\u001b[39m>\u001b[39m Any:\n\u001b[1;32m 931\u001b[0m \u001b[39m \u001b[39m\u001b[39m'''\u001b[39;00m\n\u001b[1;32m 932\u001b[0m \u001b[39m Evaluate the expression using the forward method and assign the result to the value attribute.\u001b[39;00m\n\u001b[1;32m 933\u001b[0m \n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 939\u001b[0m \u001b[39m Any: The result of the forward method.\u001b[39;00m\n\u001b[1;32m 940\u001b[0m \u001b[39m '''\u001b[39;00m\n\u001b[0;32m--> 941\u001b[0m \u001b[39mreturn\u001b[39;00m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mforward(\u001b[39m*\u001b[39;49margs, \u001b[39m*\u001b[39;49m\u001b[39m*\u001b[39;49mkwargs)\n", - "File \u001b[0;32m~/workspace/symbolicai/symai/components.py:164\u001b[0m, in \u001b[0;36mTrace.forward\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 162\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mforward\u001b[39m(\u001b[39mself\u001b[39m, \u001b[39m*\u001b[39margs, \u001b[39m*\u001b[39m\u001b[39m*\u001b[39mkwargs) \u001b[39m-\u001b[39m\u001b[39m>\u001b[39m Expression:\n\u001b[1;32m 163\u001b[0m Expression\u001b[39m.\u001b[39mcommand(verbose\u001b[39m=\u001b[39m\u001b[39mTrue\u001b[39;00m, engines\u001b[39m=\u001b[39m\u001b[39mself\u001b[39m\u001b[39m.\u001b[39mengines)\n\u001b[0;32m--> 164\u001b[0m res \u001b[39m=\u001b[39m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mexpr(\u001b[39m*\u001b[39;49margs, \u001b[39m*\u001b[39;49m\u001b[39m*\u001b[39;49mkwargs)\n\u001b[1;32m 165\u001b[0m Expression\u001b[39m.\u001b[39mcommand(verbose\u001b[39m=\u001b[39m\u001b[39mFalse\u001b[39;00m, engines\u001b[39m=\u001b[39m\u001b[39mself\u001b[39m\u001b[39m.\u001b[39mengines)\n\u001b[1;32m 166\u001b[0m \u001b[39mreturn\u001b[39;00m res\n", - "File \u001b[0;32m~/workspace/symbolicai/symai/symbol.py:941\u001b[0m, in \u001b[0;36mExpression.__call__\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 930\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39m__call__\u001b[39m(\u001b[39mself\u001b[39m, \u001b[39m*\u001b[39margs, \u001b[39m*\u001b[39m\u001b[39m*\u001b[39mkwargs) \u001b[39m-\u001b[39m\u001b[39m>\u001b[39m Any:\n\u001b[1;32m 931\u001b[0m \u001b[39m \u001b[39m\u001b[39m'''\u001b[39;00m\n\u001b[1;32m 932\u001b[0m \u001b[39m Evaluate the expression using the forward method and assign the result to the value attribute.\u001b[39;00m\n\u001b[1;32m 933\u001b[0m \n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 939\u001b[0m \u001b[39m Any: The result of the forward method.\u001b[39;00m\n\u001b[1;32m 940\u001b[0m \u001b[39m '''\u001b[39;00m\n\u001b[0;32m--> 941\u001b[0m \u001b[39mreturn\u001b[39;00m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mforward(\u001b[39m*\u001b[39;49margs, \u001b[39m*\u001b[39;49m\u001b[39m*\u001b[39;49mkwargs)\n", - "\u001b[1;32m/Users/xpitfire/workspace/symbolicai/notebooks/News.ipynb Cell 16\u001b[0m line \u001b[0;36m6\n\u001b[1;32m 63\u001b[0m vals\u001b[39m.\u001b[39mappend(\u001b[39mstr\u001b[39m(news))\n\u001b[1;32m 64\u001b[0m res \u001b[39m=\u001b[39m Symbol(vals)\u001b[39m.\u001b[39mcluster()\n\u001b[0;32m---> 65\u001b[0m sym \u001b[39m=\u001b[39m res\u001b[39m.\u001b[39;49mmap()\n\u001b[1;32m 66\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39mnot\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mrender_:\n\u001b[1;32m 67\u001b[0m \u001b[39mreturn\u001b[39;00m sym\n", - "\u001b[0;31mAttributeError\u001b[0m: 'Symbol' object has no attribute 'map'" - ] - } - ], - "source": [ - "expr = Log(Trace(news))\n", - "res = expr()\n", - "os.makedirs('results', exist_ok=True)\n", - "path = os.path.abspath('results/news.html')\n", - "res.save(path, replace=False)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Streaming over a PDF File" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Another example is to read in a PDF file and extract the text from it to create a website based on its content." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from ..examples.paper import Paper" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The process is fairly similar to the news generator. We first read in the PDF file and then stream the text through a sequence of operations. The text is then cleaned and the sentences are extracted. The sentences are then clustered and labeled. The labeled clusters are then recombined to return a rendered HTML format." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "paper = Paper(path='examples/paper.pdf')\n", - "expr = Log(Trace(paper))\n", - "res = expr(slice=(1, 1))\n", - "os.makedirs('results', exist_ok=True)\n", - "path = os.path.abspath('results/news.html')\n", - "res.save(path, replace=False)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "continualrl", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.13" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "7f6e76e437f50039fcb1dabeb26a40fb80edddddd3448a5d408bb52a844f2e97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/Queries.ipynb b/symbolicai-main/symbolicai-main/legacy/notebooks/Queries.ipynb deleted file mode 100644 index d027792cd37bca2f41d24e591aee91311685d6fb..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/Queries.ipynb +++ /dev/null @@ -1,418 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "/Users/ryang/Work/ExtensityAI/symbolicai/notebooks\n", - "Configuration file: /Users/ryang/.symai/symai.config.json\n" - ] - } - ], - "source": [ - "import os\n", - "import warnings\n", - "warnings.filterwarnings('ignore')\n", - "print(os.getcwd())\n", - "from symai import *\n", - "from IPython.display import display\n", - "from examples.sql import SQL\n", - "sql = SQL()" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## SQL Example" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `SQL` expression is defined and passes as a global context the syntax of the SQL language. The SQL expression is then used to generate queries based on the given context. We can then use the generated queries to get data from a database." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The following query is sent to the neural computation engine and creates a query based on the given context:" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "val = None\n", - "def _fun(x):\n", - " global val\n", - " val = x\n", - "Symbol._metadata.input_handler = _fun" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "<class symai.symbol.Symbol at 0x176022ad0>(value=Ich habe diesen Kurs.)" - ], - "text/plain": [ - "(value=Ich habe diesen Kurs.)" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Symbol('I have this class').translate('German')" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "<class examples.sql.SQL at 0x300e42b90>(value=SQL: SELECT * \n", - "FROM Members \n", - "WHERE age > 30)" - ], - "text/plain": [ - "(value=SQL: SELECT * \n", - "FROM Members \n", - "WHERE age > 30)" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "q = sql('Select all users above the age of 30 from the Members table.'); display(q)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can now try to further manipulate the result by asking the model to incorporate additional information, such as filtering to a specific time range:" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "<class examples.sql.SQL at 0x103eebe80>(value=SQL: SELECT * \n", - "FROM Membe ... - INTERVAL 10 MINUTE)" - ], - "text/plain": [ - "(value=SQL: SELECT * \n", - "FROM Membe ... - INTERVAL 10 MINUTE)" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "res = q << 'and limit the query to the last 10 minutes'\n", - "display(res)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can also try to remove unwanted fields from the generated query. Notice how the model tries to remove not only the given statement but attributes associated with them:" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "<class examples.sql.SQL at 0x103eebe80>(value=SQL: SELECT * \n", - "FROM Members \n", - "WHERE age > 30)" - ], - "text/plain": [ - "(value=SQL: SELECT * \n", - "FROM Members \n", - "WHERE age > 30)" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "res -= ' AND ...'\n", - "display(res)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And we can now even convert our query to other familiar domain specific languages, such as `SQL` or `ActiveRecord`:" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "<class examples.sql.SQL at 0x176023c40>(value=Members.where("age > ?", 30))" - ], - "text/plain": [ - "(value=Members.where(\"age > ?\", 30))" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "sql_res = res.convert(\"ActiveRecord\")\n", - "display(sql_res)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To wrap things up, we might want to go back full circle and ask the model to generate again the explanation based on the given query:" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "<class examples.sql.SQL at 0x300e42e60>(value=The query selects all col ... lue greater than 30.)" - ], - "text/plain": [ - "(value=The query selects all col ... lue greater than 30.)" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "answer_doc = res.query(\"What does this query do?\")\n", - "display(answer_doc)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Ask it in natural language to modify the query:" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "<class examples.sql.SQL at 0x300e43340>(value=SQL: SELECT * \n", - "FROM Membe ... E age > 30 \n", - "LIMIT 30)" - ], - "text/plain": [ - "(value=SQL: SELECT * \n", - "FROM Membe ... E age > 30 \n", - "LIMIT 30)" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "answer = res.query(\"How can you limit the number of results to 30 for an SQL query?\")\n", - "display(answer)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Even translate the explanation to a different language on the fly:" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "<class symai.symbol.Symbol at 0x300e43610>(value=Die Abfrage wählt alle Sp ... t größer als 30 hat.)" - ], - "text/plain": [ - "(value=Die Abfrage wählt alle Sp ... t größer als 30 hat.)" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "locale = Symbol(answer_doc).translate('German')\n", - "display(locale)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Fixing the query on the fly if something goes wrong or the user quickly wants to adapt a query:" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "sql.adapt(context=\"\"\"Explanation: Never allow SELECT *, always use LIMIT to a max of x <= 50 entries, where x is the user specified limit.\"\"\");" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "<class examples.sql.SQL at 0x300ef12a0>(value=SQL: SELECT *\n", - "FROM Members\n", - "WHERE age > 30\n", - "LIMIT 50)" - ], - "text/plain": [ - "(value=SQL: SELECT *\n", - "FROM Members\n", - "WHERE age > 30\n", - "LIMIT 50)" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "res = sql('Select all users above the age of 30 from the Members table.')\n", - "display(res)" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [], - "source": [ - "sql.clear()" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "<class examples.sql.SQL at 0x302e514b0>(value=SQL: SELECT * FROM Members WHERE age > 30)" - ], - "text/plain": [ - "(value=SQL: SELECT * FROM Members WHERE age > 30)" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "res = sql('Select all users above the age of 30 from the Members table.')\n", - "display(res)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "continualrl", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.8" - }, - "vscode": { - "interpreter": { - "hash": "7f6e76e437f50039fcb1dabeb26a40fb80edddddd3448a5d408bb52a844f2e97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/TTS_Persona.ipynb b/symbolicai-main/symbolicai-main/legacy/notebooks/TTS_Persona.ipynb deleted file mode 100644 index ac464b4f003514959ffb7b6a3a4d140ecf21dd91..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/TTS_Persona.ipynb +++ /dev/null @@ -1,403 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "from symai.extended.personas import PersonaBuilder\n", - "from symai.extended.personas import Dialogue\n", - "from symai.extended.api_builder import APIExecutor\n", - "from symai.extended.personas.student import MaxTenner\n", - "from symai import Interface" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Text-to-speech" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "tts = Interface('tts')" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "" - ], - "text/plain": [ - "(value=)" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "tts(\"hello world\", path='./marius_tts.mp3', voice='echo')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Conversations" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [], - "source": [ - "from symai.extended import Conversation" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "INFO:WDM:====== WebDriver manager ======\n", - "2023-11-17 09:24:37,290 ====== WebDriver manager ======\n", - "2023-11-17 09:24:37,290 ====== WebDriver manager ======\n", - "INFO:WDM:Get LATEST chromedriver version for google-chrome\n", - "2023-11-17 09:24:37,649 Get LATEST chromedriver version for google-chrome\n", - "2023-11-17 09:24:37,649 Get LATEST chromedriver version for google-chrome\n", - "INFO:WDM:Get LATEST chromedriver version for google-chrome\n", - "2023-11-17 09:24:37,717 Get LATEST chromedriver version for google-chrome\n", - "2023-11-17 09:24:37,717 Get LATEST chromedriver version for google-chrome\n", - "INFO:WDM:Driver [/Users/xpitfire/.wdm/drivers/chromedriver/mac64/119.0.6045.105/chromedriver-mac-x64/chromedriver] found in cache\n", - "2023-11-17 09:24:37,781 Driver [/Users/xpitfire/.wdm/drivers/chromedriver/mac64/119.0.6045.105/chromedriver-mac-x64/chromedriver] found in cache\n", - "2023-11-17 09:24:37,781 Driver [/Users/xpitfire/.wdm/drivers/chromedriver/mac64/119.0.6045.105/chromedriver-mac-x64/chromedriver] found in cache\n", - "DEBUG:selenium.webdriver.common.service:Started executable: `/Users/xpitfire/.wdm/drivers/chromedriver/mac64/119.0.6045.105/chromedriver-mac-x64/chromedriver` in a child process with pid: 1890\n" - ] - } - ], - "source": [ - "crawler = Interface('selenium') # get data from web\n", - "data = crawler('https://github.com/ExtensityAI/symbolicai')" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "conv = Conversation(data) # initialize conversation with data" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Project Title: \"SymbolicAI: Integrating the Power of Neuro-Symbolic Computing Into Large Language Models\"\n", - "\n", - "Introduction:\n", - "At the forefront of cognitive and computational advancements lies SymbolicAI, an innovative library crafted to revolutionize the way we perceive and interact with machine intelligence. Embarking on a journey where classical programming synergizes with the potent capabilities of neuro-symbolic computing, we aim to seamlessly blend the precision of symbolic reasoning with the fluid adaptability of machine learning. Our mission is to empower developers, researchers, and innovators with a comprehensive toolbox— one that paves the way for constructing applications that not only think but reason, deduce, and evolve.\n", - "\n", - "SymbolicAI has been meticulously engineered to serve as the backbone for applications that require the critical integration of traditional programming methods and the advanced, intuitively designed differentiable programs that lie at the heart of modern artificial intelligence. The library stands as a testament to our commitment to providing a rich, compositional framework that invites contributions and collaboration, furthering research at the nexus of neuro-symbolic exploration.\n", - "\n", - "Request for Funding:\n", - "Our ambitious endeavors to refine and enhance SymbolicAI necessitate considerable funding. This financial support would underwrite the technical development, including expanding the library's capabilities, maintaining the infrastructure, testing and optimizing the framework for robust, industry-level deployment, and ensuring that SymbolicAI retains its cutting-edge relevance.\n", - "\n", - "Investment in SymbolicAI also represents a strategic move towards positioning Large Language Models (LLMs) as central figures within the computational landscape. Funding will facilitate the next leap in our journey, as we seek to create a singular platform where developers can not only code but also instruct, probe, and educate the neuro-symbolic models—entrusting them with the responsibility to augment human potential across various domains.\n", - "\n", - "Request for Community Visibility:\n", - "Visibility within the community is paramount for the propagation of any groundbreaking technology. As such, we ardently seek avenues to uplift the presence of SymbolicAI within the vast expanse of the tech community. Through featured articles, high-profile open-source repositories, collaborations with academic institutions, and presentations at industry conferences, we intend to illuminate the potential that SymbolicAI holds.\n", - "\n", - "Our aspiration is to ignite conversations, encourage scrutiny and discourse, and invite the open-source community's collective brilliance to refine and steer SymbolicAI towards unforeseen horizons. We believe that heightened community visibility will unlock doors to innovative applications, invoke diverse perspectives, and spur an evolution that resonates with the very core of our technological ethos.\n", - "\n", - "Request for Development Support:\n", - "The evolution of SymbolicAI hinges not only on conceptual breakthroughs but also on the collective contribution of skilled developers who can iterate, debug, and innovate. We thus extend our invitation to developers who harbor a passion for AI and wish to contribute to the exponential growth of SymbolicAI.\n", - "\n", - "We seek individuals with expertise in neuro-symbolic computing, large language models, and cognitive architecture, as well as those who are proficient in Python, machine learning frameworks, and differencing programming techniques. Collaborative development will enable us to expand the library's functionality, address community feedback, enhance user experience, and modulate the resource to resonate with industry needs.\n", - "\n", - "In conclusion, we assert that the SymbolicAI library is not merely a technological venture; it is a collaborative odyssey that, with adequate funding, community visibility, and development support, has the potential to redefine our interaction with machine intelligence. The prospect of what can be achieved is boundless, contingent on the belief and backing of stakeholders who share our vision—a vision that speaks of an era where neuro-symbolic computing and LLMs become the keystones of cognitive technology.\n" - ] - } - ], - "source": [ - "conv(\"\"\"[Task]\n", - "Write an elaborate project introduction for the project proposal.\n", - "\n", - "Include the request for:\n", - "- funding\n", - "- community visibility\n", - "- development support\n", - "\n", - "\"\"\");" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### API Executor" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": {}, - "outputs": [], - "source": [ - "source = APIExecutor() # creates code on the fly and executes it\n", - "data = source('Fetch data from URL https://www.ykilcher.com/') # interprets the instruction to generate a HTTP request" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "def run(url: str) -> str: # [MANAGED] entry point cannot be changed\n", - " # [MANAGED-BEGIN] mandatory imports here\n", - " import traceback\n", - " import requests\n", - " from symai import Function\n", - " # [MANAGED-END] mandatory imports here\n", - "\n", - " try: # [MANAGED] must contain this line, do not change\n", - " # Make a GET request to fetch data from the given URL\n", - " response = requests.get(url)\n", - " \n", - " # Check if the response was successful\n", - " if response.status_code != 200:\n", - " return f\"Failed to fetch data: {response.status_code}\"\n", - " \n", - " # If successful, return the content of the response\n", - " return response.text # Returning the content as text\n", - " except Exception as e: # [MANAGED] must catch all exceptions and return them as string\n", - " tb = traceback.format_exc() # [MANAGED] return full error stack trace as string\n", - " return tb # [MANAGED] return tb as string, do not change\n", - "\n", - "# [STATIC CONTEXT] DO NOT CHANGE ANYTHING BELOW THIS LINE\n", - "value = \"https://www.ykilcher.com/\" # The URL from the instruction is provided here\n", - "res = run(value) # [MANAGED] must contain this line, do not change\n" - ] - } - ], - "source": [ - "print(source._code)" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "metadata": {}, - "outputs": [], - "source": [ - "text = data.extract('Plain text') # extracts the plain text from the entire HTML page" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "text.value[:100] # show the fetched data" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "crawler = Interface('selenium') # init selenium interface" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "metadata": {}, - "outputs": [], - "source": [ - "additional_info = crawler('https://scholar.google.com/citations?user=T3Ji6P4AAAAJ')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Persona Creator" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [], - "source": [ - "builder = PersonaBuilder() # generate based on crawled data a persona\n", - "YannicKilcher = builder('Yannic Kilcher', description=text | additional_info) # builds a persona based on the extracted text and fills in blanks with hallucinated data" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "Yannic Kilcher is an athletic, approachable, and articulate Machine Learning Ph.D. student at ETH Zurich who excels at making complex AI concepts accessible on his YouTube channel." - ], - "text/plain": [ - "(value=Yannic Kilcher is an athletic, approachable, and articulate Machine Learning Ph.D. student at ETH Zurich who excels at making complex AI concepts accessible on his YouTube channel.)" - ] - }, - "execution_count": 31, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "yannic = YannicKilcher() # instanciate a newly generated persona\n", - "yannic.summarize() # show the persona summary" - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "metadata": {}, - "outputs": [], - "source": [ - "max = MaxTenner() # create a pre-defined persona\n", - "dialogue = Dialogue(max, yannic, n_turns=2) # run a dialogue between the two personas" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[Max Tenner::]: Hey Yannic, tell me more about your latest video where every instruction is a prompt\n", - "\n", - "[Yannic Kilcher::]: Hey Max, I'm glad you asked! My latest video explores the concept of a \"Prompt-based Learning System.\" Essentially, it's an AI model that operates entirely on prompts, which are guiding instructions in natural language. This system is intriguing because it reflects a more intuitive way of human-computer interaction, much like how we naturally communicate with one another.\n", - "\n", - "By using prompts as instructions, we can direct the AI to perform specific tasks without hard-coding the behaviors. This approach also showcases the versatility of language models that are capable of understanding and executing a wide range of commands based on the context provided by these prompts.\n", - "\n", - "In the video, I dive into how this technology works, its potential applications, and some of the challenges that come with it. For instance, crafting an effective prompt can be an art in itself, and the AI’s response can sometimes be unpredictable. But the advantages, such as ease of use and adaptability, could make this a staple in how we leverage AI in the future.\n", - "\n", - "As you're also someone who's passionate about making technology understandable and accessible, I thought this topic might resonate with you, Max. Would love to hear your thoughts on this!\n", - "\n", - "[Max Tenner::]: That sounds super interesting, Yannic! The concept of using natural language to guide AI mirrors how I like to approach tech – intuitively and creatively. I can see how a Prompt-based Learning System could become incredibly user-friendly, especially for those who may be intimidated by traditional coding.\n", - "\n", - "The potential for varied applications seems massive. We could use it for everything from personal assistants to more complex tasks like data analysis or language translation, all with a simple prompt. And you're right, crafting prompts is indeed an art. It's like choosing the perfect command in a video game to advance the story or unlock a new ability.\n", - "\n", - "Your point about unpredictability is something I've encountered while tinkering with code or even when coaching my junior football team – you can give instructions, but the outcome can always vary! Maybe I'll experiment with this kind of AI for organizing game strategies.\n", - "\n", - "I'll definitely check out your video in full and share it with my sister Lucy, who's into coding. It could spark some great projects or at least give us plenty to talk about. Keep up the great work, Yannic. Your content always gets my brain gears turning!\n", - "\n", - "[Yannic Kilcher::]: Appreciate it, Max! I'm always excited to share ideas that could potentially inspire or facilitate new ways of interacting with technology. And I love the analogy of using commands in video games — it's a great way to look at it. The diversity of instructions and the corresponding actions in games really do mirror the dynamics of prompt-based AI. \n", - "\n", - "It's also great to hear you're thinking of applying this to your coaching. Sports strategies are dynamic and complex, which makes them a fascinating use case for AI. The adaptability of prompt-based systems could help in analyzing game patterns or optimizing training programs.\n", - "\n", - "It makes me happy to know that my content sparks conversations and ideas, especially across different fields and interests. I'm really looking forward to hearing any insights or experiences you and Lucy might have after discussing the video. And who knows, this could lead to practical applications in coding or even new strategies on the football field.\n", - "\n", - "Thanks for the support, Max, and for the engaging discussion. Your perspective always adds valuable depth to the topic at hand. Keep the feedback coming!\n", - "\n" - ] - }, - { - "data": { - "text/plain": [ - "('demos/tmp/output.mp3', <_io.BufferedRandom name='demos/tmp/output.mp3'>)" - ] - }, - "execution_count": 36, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "dialogue(\"Hey Yannic, tell me more about your latest video where every instruction is a prompt\"); # initializes and run the dialogue\n", - "dialogue.render('demos') # render an audio file of the dialogue" - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "('demos/tmp/output.mp3', <_io.BufferedRandom name='demos/tmp/output.mp3'>)" - ] - }, - "execution_count": 37, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "dialogue.render('demos', overwrite=True) # render an audio file of the dialogue" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "symai", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.13" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/Lean engine.png b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/Lean engine.png deleted file mode 100644 index 2453e4e032ee2aab93a14df5a5f830356914ad1a..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/Lean engine.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5cdf1fcfe61920fd363844b74948c379f735a0f975dd6e00614a1adddefe2104 -size 195166 diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/a_star.txt b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/a_star.txt deleted file mode 100644 index d9e6c24297b7bcf6969b258ab22261255c5c46e8..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/a_star.txt +++ /dev/null @@ -1,49 +0,0 @@ -function reconstruct_path(cameFrom, current) - total_path := {current} - while current in cameFrom.Keys: - current := cameFrom[current] - total_path.prepend(current) - return total_path - -// A* finds a path from start to goal. -// h is the heuristic function. h(n) estimates the cost to reach goal from node n. -function A_Star(start, goal, h) - // The set of discovered nodes that may need to be (re-)expanded. - // Initially, only the start node is known. - // This is usually implemented as a min-heap or priority queue rather than a hash-set. - openSet := {start} - - // For node n, cameFrom[n] is the node immediately preceding it on the cheapest path from start - // to n currently known. - cameFrom := an empty map - - // For node n, gScore[n] is the cost of the cheapest path from start to n currently known. - gScore := map with default value of Infinity - gScore[start] := 0 - - // For node n, fScore[n] := gScore[n] + h(n). fScore[n] represents our current best guess as to - // how cheap a path could be from start to finish if it goes through n. - fScore := map with default value of Infinity - fScore[start] := h(start) - - while openSet is not empty - // This operation can occur in O(Log(N)) time if openSet is a min-heap or a priority queue - current := the node in openSet having the lowest fScore[] value - if current = goal - return reconstruct_path(cameFrom, current) - - openSet.Remove(current) - for each neighbor of current - // d(current,neighbor) is the weight of the edge from current to neighbor - // tentative_gScore is the distance from start to the neighbor through current - tentative_gScore := gScore[current] + d(current, neighbor) - if tentative_gScore < gScore[neighbor] - // This path to neighbor is better than any previous one. Record it! - cameFrom[neighbor] := current - gScore[neighbor] := tentative_gScore - fScore[neighbor] := tentative_gScore + h(neighbor) - if neighbor not in openSet - openSet.add(neighbor) - - // Open set is empty but goal was never reached - return failure diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/abstract.py b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/abstract.py deleted file mode 100644 index 86d641f9399d7f37714dddb28f91239f0fc56144..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/abstract.py +++ /dev/null @@ -1,38 +0,0 @@ -from symai import * -from symai.components import * - -HEADER_DESCRIPTION = """Design a web app with HTML, CSS and inline JavaScript. -Use dark theme and best practices for colors, text font, etc. -Use Bootstrap for styling. -Do NOT remove the {{placeholder}} tag and do NOT add new tags into the body!""" - - -class Abstract(Expression): - - def static_context(self): - return HEADER_DESCRIPTION - - def __init__(self, path: str, filters: List[Expression] = [], **kwargs): - super().__init__(**kwargs) - self.path = path - filters = filters if isinstance(filters, List) or isinstance(filters, tuple) else [filters] - self.data_stream = Stream(Sequence( - Clean(), - Translate(), - *filters, - Compose(f'Write a paper summary. Keep all information with the corresponding citations:\n'), - )) - - def forward(self, **kwargs) -> Symbol: - res = self.open(self.path, **kwargs) - data = '' - template = self.header_style(self.html_template) - paragraphs = [] - for section in self.data_stream(res): - key = section.unique(paragraphs) - paragraphs.append(str(key)) - self.html_template_seq.template_ = str(template) - kwargs['dynamic_context'] = f'Context: Create a summary paragraph about {str(key)}\n' - data += '\n'.join([str(s) for s in self.html_stream(section, **kwargs)]) - res = Symbol(str(template).replace('{{placeholder}}', data)) - return res diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/audio.mp3 b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/audio.mp3 deleted file mode 100644 index 30b1c94083cd2b74034436f5d67e295af7da00a7..0000000000000000000000000000000000000000 Binary files a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/audio.mp3 and /dev/null differ diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/dbpedia_samples.jsonl b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/dbpedia_samples.jsonl deleted file mode 100644 index a6ce1dff4434f785e7a511242a793017f92317b0..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/dbpedia_samples.jsonl +++ /dev/null @@ -1,200 +0,0 @@ -{"prompt": " Morada Limited is a textile company based in Altham Lancashire. Morada specializes in curtains.\n==>\n", "completion": "Company"} -{"prompt": " The Armenian Mirror-Spectator is a newspaper published by the Baikar Association in Watertown Massachusetts.\n==>\n", "completion": "WrittenWork"} -{"prompt": " Mt. Kinka (\u91d1\u83ef\u5c71 Kinka-zan) also known as Kinkazan is located in the heart of the city of Gifu Gifu Prefecture Japan and rises to a height of 329 m (1079 ft). Previously called Mt. Inaba (\u7a32\u8449\u5c71 Inaba-yama) it has long served as the representative symbol of Gifu. It stands along the Nagara River creating bountiful nature within the city. Though it is the most famous mountain in the city Mount Dodo to the north is the tallest.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " Planning the Play of a Bridge Hand is a book on contract bridge co-written by Canadian teacher and author Barbara Seagram and British author David Bird. It was published by Master Point Press in 2009.The book teaches novice bridge players some basic techniques of declarer play including suit establishment ruffing losers and the finesse.\n==>\n", "completion": "WrittenWork"} -{"prompt": " Wang Yuanping (born 8 December 1976) is a retired Chinese athlete who specialised in the 800 metres. She won several medals at the regional level.Her personal bests in the event are 2:00.63 seconds outdoors (Jinzhou 2000) and 2:03.41 seconds indoors (Yokohama 2004).\n==>\n", "completion": "Athlete"} -{"prompt": " The Incorporated VIllage of Westhampton Beach is an incorporated village in the Town of Southampton Suffolk County New York United States. As of the 2010 census the village population was 1721.\n==>\n", "completion": "Village"} -{"prompt": " Andersons Creek is a creek in Warrandyte and Park Orchards east of Melbourne Victoria Australia. It is a tributary of the Yarra River.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " The Three Horseshoes is a public house in Drybridge Street in the Overmonnow area of Monmouth Wales. The pub has also been used as an Inn and also known as The Three Horse Shoes Inn. The building has been a Grade II Listed building since 15 August 1974. 19th century 2 storeys roughcast as stone with a hooded doorway\n==>\n", "completion": "Building"} -{"prompt": " The Brewer's Art is a Baltimore Maryland brewpub and restaurant. Opened on Friday September 13 1996. In 2008 it was named by Esquire magazine as the #1 Best Bar in America.\n==>\n", "completion": "Company"} -{"prompt": " The P\u00e2r\u00e2ul S\u0103r\u0103\u021bii is a tributary of the Cibin River in Romania.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " Jean-Fran\u00e7ois Imbernon (born October 17 1951 in Perpignan France is a retired French international rugby union player.He played as a Lock for USA Perpignan. He earned his first cap with the French national team on 7 February 1976 against Ireland at Parc des Princes.\n==>\n", "completion": "Athlete"} -{"prompt": " Le Cadeau released in Italy as Il regalo is a 1982 French and Italian film. It stars Claudia Cardinale.\n==>\n", "completion": "Film"} -{"prompt": " Mykola Kanevets (Ukrainian: \u041c\u0438\u043a\u043e\u043b\u0430 \u041a\u0430\u043d\u0456\u0432\u0435\u0446\u044c) is the Artistic Director and Ballet Master of the Cheremosh Ukrainian Dance Company in Edmonton Alberta Canada.A native of Kiev Ukraine Mykola attended the National University of Culture and Performing Arts in Kiev Ukraine where he graduated from the Faculty of Choreography with the distinction of Ballet Master and Choreographer.\n==>\n", "completion": "Artist"} -{"prompt": " Jenna Rose Swerdlow (born September 28 1998) is an American teenage singer who gained media attention as a pre-teen with her single My Jeans. After the video went viral on YouTube and received 14 million views Swerdlow is considered a semi-viral star.\n==>\n", "completion": "Artist"} -{"prompt": " The Spice of Life is a smooth jazz studio album by Earl Klugh released in April 2008. The album received a Grammy nomination for Best Pop Instrumental Album at the 51st Grammy Awards in 2009.\n==>\n", "completion": "Album"} -{"prompt": " Lomatium macrocarpum is a perennial flowering plant in the carrot family known by the common names bigseed lomatium biscuit root or even bigseed biscuitroot. It is native to much of western North America where it can be found in various types of habitat including the grasslands of the Great Plains. It is spreading or erect perennial herb growing up to about half a meter long with hairy gray-green herbage.\n==>\n", "completion": "Plant"} -{"prompt": " Physena is the sole genus of the flowering plant family Physenaceae. It contains two species of shrubs and small trees which are endemic to Madagascar. The APG II system of 2003 (unchanged from the APG system of 1998) does recognize this family and assigns it to the order Caryophyllales in the clade core eudicots.\n==>\n", "completion": "Plant"} -{"prompt": " David John Weatherley (born 1 March 1939) is a New Zealander actor known for his roles as Spencer the butler and the voice of Benglo the Fearcat in Power Rangers Operation Overdrive and Barliman Butterbur in The Lord of the Rings: The Fellowship of the Ring.Weatherley was born in London England and moved to Canada for a military career. He eventually moved to New Zealand to engage in a theatre acting career.\n==>\n", "completion": "Artist"} -{"prompt": " Draba incrassata is an uncommon species of flowering plant in the mustard family known by the common name Sweetwater Mountains draba. It is endemic to California where it is known mainly from the Sweetwater Mountains of Mono County. It grows in alpine rock fields on the barren high mountain peaks. Draba incrassata is a small perennial herb forming mats of thick oval-shaped leaves.\n==>\n", "completion": "Plant"} -{"prompt": " Pimelea ferruginea is a small shrub native to southwest Western Australia. It was described by Labillardiere in 1805.\n==>\n", "completion": "Plant"} -{"prompt": " Lindsay Ell is a country music singer songwriter and guitarist from Calgary Alberta.She performed at the South by Southwest music festival held in Austin Texas in March 2009 the welcome reception of the 2009 Juno Awards held in Vancouver British Columbia and was also a featured artist at the 2010 Winter Olympics.\n==>\n", "completion": "Artist"} -{"prompt": " Scopula fuscata is a moth of the Geometridae family. It is found from south-western Saskatchewan west to British Columbia and south to California and Arizona. The habitat consists of montane areas including foothills.The wingspan is 24-28 mm. The wings and body are light tan sprinkled with darker yellow-brown or grey-brown scales. There is one generation per year with adults on wing in late June and early July in the northern part of the range.\n==>\n", "completion": "Animal"} -{"prompt": " Oxmoor Center is a Louisville Kentucky shopping mall located at 7900 Shelbyville Road in eastern Louisville.\n==>\n", "completion": "Building"} -{"prompt": " Ghostquake (also known as Haunted High) is a 2012 American made-for-television horror film produced by Syfy. The film was directed by Jeffrey Lando and written by Paul A. Birkett and Anthony C. Ferrante. The film stars Danny Trejo and MC Gainey. It follows a group of high school students trying to escape the wrath of a few ghastly spirits following an earthquake at their school Holloman High School.\n==>\n", "completion": "Film"} -{"prompt": " The Masonic Temple in Great Falls Montana is a building from 1914. It was listed on the National Register of Historic Places in 2000.Address is 821 Central Avenue Great Falls Motana 59401 Phone number is 453-9080.Cascade No. 34 meets 2nd and 4th Tuesdays at 7:30pm Sept-June.Euclid No. 58 meets year-round 1st and 3rd Tuesdays at 7:30pm Sept-May 3rd Tuesdays at 7:30pm June-Aug. Delta No. 128 meets 2nd Wednesdays at 7:30pm Sept-June.\n==>\n", "completion": "Building"} -{"prompt": " Harold Frederick Weaver Hawkins (1893-1977) was an English painter who specialized in ambitious sometimes mural-sized modernist allegories of morality for an age of atomic warfare and global over-population.\n==>\n", "completion": "Artist"} -{"prompt": " Robert Murray Waddington (24 October 1927 \u2013 15 March 2007) was Dean of Manchester in the last quarter of the 20th century.Born in Bognor Regis on 24 October 1927 he was educated at Dulwich College Selwyn College Cambridge and Ely Theological College. Ordained in 1954 he began his career at St John\u2019s Bethnal Green. Afterwards he was Chaplain at Slade School in Warwick Queensland. He returned to England in 1959 to join the Oratory of the Good Shepherd an order of celibate priests.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Jason Gary King (born 13 April 1985 in Maidstone England) is a speedway rider who was formerly the club captain of Newcastle Diamonds in the British Premier League. His brother Daniel is also a speedway rider.\n==>\n", "completion": "Athlete"} -{"prompt": " The African Queen is a 1951 adventure film adapted from the 1935 novel of the same name by C. S. Forester. The film was directed by John Huston and produced by Sam Spiegel and John Woolf. The screenplay was adapted by James Agee John Huston John Collier and Peter Viertel. It was photographed in Technicolor by Jack Cardiff and had a music score by Allan Gray.\n==>\n", "completion": "Film"} -{"prompt": " The Fiat Barchetta (Italian pronunciation: [\u02c8fiat bar\u02c8ketta]) (Type 183) is a roadster produced by the Italian manufacturer Fiat from 1995 to 2005 (though production was paused between May 2002 and 2004). Barchetta in Italian means 'little boat'.\n==>\n", "completion": "MeanOfTransportation"} -{"prompt": " Sardar Vallabhbhai Patel National Memorial is a museum and exhibition centre dedicated to Sardar Vallabhbhai Patel at Moti Shahi Mahal located in Shahibaug Ahmedabad Gujarat. Moti Shahi Mahal was constructed by Mughal emperor Shahjahan between 1618 and 1622. It is surrounded by a garden.\n==>\n", "completion": "Building"} -{"prompt": " Under Cover 2 is the 5th solo album of Joe Lynn Turner released in 1999. Just like Under Cover the album consists mainly of covers of Turner's favourite artists.\n==>\n", "completion": "Album"} -{"prompt": " The Atakora River is a tributary of Lake Volta in Ghana it flows about 60 km east to the Lake Volta. Its entire course is in south Ghana.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " Death from Above is a 2011 horror film by director Bruce Koehler. The film features professional wrestling stars Kurt Angle Sid Eudy James Storm Matt Morgan Terry Gerin and Jessica Kresa.\n==>\n", "completion": "Film"} -{"prompt": " Portraits of Cuba is an album by Cuban musician Paquito D'Rivera released through Chesky Records in 1996. In 1997 the album won D'Rivera the Grammy Award for Best Latin Jazz Performance.\n==>\n", "completion": "Album"} -{"prompt": " Jimmy Cross (17 November 1938 - 8 October 1978) was an American radio producer and singer who attained a minor Billboard Hot 100 hit with the novelty song I Want My Baby Back in 1965. He was born in Dothan Alabama[citation needed] and became the producer of the syndicated radio series Country Concert.I Want My Baby Back was originally issued on the Tollie label and reached #92 on the Billboard Hot 100 in February 1965.\n==>\n", "completion": "Artist"} -{"prompt": " Timothy Floyd Tim Burchett (born August 25 1964) is an American Republican politician currently the mayor of Knox County Tennessee. He previously served in Tennessee General Assembly first in the Tennessee House of Representatives and later in the Tennessee State Senate in which he represented Tennessee's District 7 part of Knox County. On August 5 2010 Burchett was elected mayor of Knox County replacing Mike Ragsdale.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Daniel Lawrence Dan Whitney (born February 17 1963) best known by his stage name and character Larry the Cable Guy is an American stand-up comedian actor voice actor and former radio personality.\n==>\n", "completion": "Artist"} -{"prompt": " Renealmia is a plant genus in the family Zingiberaceae. Species include: Renealmia alpinia Renealmia aurantifera Renealmia cernua Renealmia dolichocalyx Renealmia oligotricha Renealmia sessilifolia Renealmia thrysoidesE.g. Alpinia nutans was formerly placed herein too.\n==>\n", "completion": "Plant"} -{"prompt": " Jeff Chapman (born July 17 1969 in Brunswick Georgia) is the bass singer for the Kingdom Heirs. He has been a member of the group since 2002. He has previously traveled with Bob Wills The Sound The Anchormen and The Blackwoods.He has twice been nominated as favorite bass in the Singing News fan awards.Chapman has a wife Angie two sons Justin and Sean and daughter Taylor.\n==>\n", "completion": "Artist"} -{"prompt": " Arenaria ursina is a species of flowering plant in the pink family known by the common name Bear Valley sandwort.\n==>\n", "completion": "Plant"} -{"prompt": " Living Fossil is a classic science fiction story on the concepts of human extinction and future evolution by L. Sprague de Camp. It was first published in the magazine Astounding Science-Fiction for February 1939. It first appeared in book form in the anthology A Treasury of Science Fiction (Crown Publishers 1948); it later appeared in the anthologies Gates to Tomorrow (Atheneum 1973) and The SFWA Grand Masters Volume 1 (Tor Books 1999).\n==>\n", "completion": "WrittenWork"} -{"prompt": " Brachyglottis huntii commonly called rautini or Chatham Island Christmas tree is a species in the Asteraceae family and is found only on the Chatham Islands in New Zealand.\n==>\n", "completion": "Plant"} -{"prompt": " Luktvatnet is a lake that lies in the northern part of the municipality of Vefsn in Nordland county Norway. The lake lies between the mountains Korgfjellet and Lukttinden about 5 kilometres (3.1 mi) south of Elsfjord. The European route E06 highway passes along the northern shore of the lake.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " The IAR 79 is a bi-engine bomber military reconnaissance aircraft with a wood and metal structure that saw service in World War II built under licence in Brasov Romania by Industria Aeronautic\u0103 Rom\u00e2n\u0103\n==>\n", "completion": "MeanOfTransportation"} -{"prompt": " Enrico Perucconi (born 4 January 1925 in Morazzone Varese Italy) was an Italian athlete who competed mainly in the 100 metres.\n==>\n", "completion": "Athlete"} -{"prompt": " Central National-Gottesman Inc. is one of the world's largest distributors of pulp paper paperboard and newsprint. The firm's products are sold in over 75 countries through a network of 43 offices located in the United States and abroad. With annual revenues exceeding $3 billion Forbes ranked Central National-Gottesman 137th in its annual list of The Largest Private Companies.\n==>\n", "completion": "Company"} -{"prompt": " The Kout Food Group is a Kuwaiti-based conglomerate founded in 1982.In Kuwait it operates franchises of Burger King Pizza Hut and Taco Bell.Its UK arm Kout Food Group Restaurants UK it operates under brands such as Burger King KFC and Maison Blanc. In August 2013 it acquired the Little Chef chain for \u00a315 million.\n==>\n", "completion": "Company"} -{"prompt": " Fab Five: The Texas Cheerleader Scandal is a Lifetime Television made-for-TV drama film starring Jenna Dewan Ashley Benson and Tatum O'Neal and directed by Tom McLoughlin. The film premiered on August 2 2008. It is based on a true story which occurred at McKinney North High School in McKinney Texas in 2006 in which five teenage cheerleaders became notorious for bullying truancies violations of the school dress code and general disrespect to the school community and authority.\n==>\n", "completion": "Film"} -{"prompt": " Qadi Mahalleh (Persian: \u0642\u0627\u062f\u064a \u0645\u062d\u0644\u0647\u200e also Romanized as Q\u0101d\u012b Ma\u1e29alleh) is a village in Pazevar Rural District Rudbast District Babolsar County Mazandaran Province Iran. At the 2006 census its population was 228 in 59 families.\n==>\n", "completion": "Village"} -{"prompt": " Eungella Dam is one of Queensland's more established freshwater fisheries. Eungella has made a name for producing extra oversized Sooty grunter and more recently Barramundi.Eungella Dam was constructed in 1969 to meet the requirements of a thermal power station at Collinsville and the town water requirement of Collinsville and Scottsville.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " The American Motor Car Company was a short-lived company in the automotive industry founded in 1906 lasting until 1913. It was based in Indianapolis Indiana United States. The American Motor Car Company pioneered the underslung design.\n==>\n", "completion": "Company"} -{"prompt": " Hawkeye & Mockingbird was a comic book ongoing series published by Marvel Comics starring superheroes Hawkeye and Mockingbird.\n==>\n", "completion": "WrittenWork"} -{"prompt": " Margaret Anderson Kelliher (born March 11 1968) is a Minnesota politician and a former member of the Minnesota House of Representatives. A member of the Minnesota Democratic\u2013Farmer\u2013Labor Party she represented District 60A which includes portions of the city of Minneapolis in Hennepin County located in the Twin Cities metropolitan area. First elected in 1999 she served until 2011 also serving as the Speaker from 2007 to 2011.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " John Whitlow Wyatt (September 27 1907 \u2013 July 16 1999) was a professional baseball pitcher. He played all or part of sixteen seasons in Major League Baseball for the Detroit Tigers (1929\u201333) Chicago White Sox (1933\u201336) Cleveland Indians (1937) Brooklyn Dodgers (1939\u201344) and Philadelphia Phillies (1945). While injuries sidetracked much of Wyatt's early career he is most famous for his performance in 1941 when his team (the Dodgers) won the National League pennant.\n==>\n", "completion": "Athlete"} -{"prompt": " William Thomas Burton (31 January 1878 in Black Rock St Michael Barbados \u2013 22 August 1946 St Michael Barbados) was a coloured West Indian cricketer best known as a member of the 1900 and 1906 West Indian tourists to England. He is generally known as Tommie Burton.He was the son of a black mother and a white father. He was brought up in Barbados and served for some years there as a practice bowler and in trial matches.\n==>\n", "completion": "Athlete"} -{"prompt": " Tulemalu Lake is a lake in Kivalliq Region Nunavut Canada.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " Sten Stjernqvist is a Swedish former footballer who played as a forward.\n==>\n", "completion": "Athlete"} -{"prompt": " David Parlett (born 1939) is a games scholar from South London who has studied both card games and board games. His published works include many popular books on games and the more academic volumes The Oxford Guide to Card Games and The Oxford History of Board Games both now out of print. Parlett also invented a number of board games the most successful of which is Hare and Tortoise (1974). The German edition was awarded Spiel des Jahres (Game of the Year) in 1979.\n==>\n", "completion": "Artist"} -{"prompt": " Karl Nabersberg (sometimes written as Carl Nabersberg) was a German youth leader.Nabersberg was the son of a Crefeld shopkeeper. In 1923 he joined the Jugendorganisation the forerunner of the Hitler Youth in his home town. On 28 December 1925 he was admitted as a member of the National Socialist German Workers' Party (member number 26269) and as a member of the Sturmabteilung.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " \u0160etonje is a village situated in Petrovac na Mlavi municipality in Serbia.\n==>\n", "completion": "Village"} -{"prompt": " Dr. Joseph de Graft-Johnson (1933\u20131999) was an engineer academic and politician. He became the Vice-President of Ghana between 1979 and 1981.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Patties Foods (previously Patties Bakery) is an Australian food manufacturing company that produces meat pies baked goods frozen fruits and pre-made desserts. Headquartered in Bairnsdale Victoria Australia Patties Foods is represented in the Australian market by the Four'N Twenty Patties Herbert Adams Creative Gourmet Nanna's and Chefs Pride brands. Patties is the largest meat pie producing company in Australia and the world.\n==>\n", "completion": "Company"} -{"prompt": " Double Butte is the 2579-foot (786 m) mountain summit distinguished by two buttes (the other at abou 2480 feet or 756 metres) in Riverside County California. It is the western most summit of a mountain range north of Winchester California east of Perris Valley and west of the San Jacinto Valley. The eastern ridge is composed primarily of metamorphic rock of the Triassic - Jurassic French Valley formation.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " Mount Carmel \u2013 Blytheswood Public School is an elementary school in the north end of Leamington Ontario Canada. It is part of the Greater Essex County District School Board and serves students from JK to Grade 8 from the communities of Blytheswood and Mount Carmel and surrounding areas.\n==>\n", "completion": "EducationalInstitution"} -{"prompt": " La combi asesina (The Killer Combination) is a 1982 Mexican film. It was directed by Gustavo Alatriste.\n==>\n", "completion": "Film"} -{"prompt": " Halimium ocymoides (basil-leaved rock rose) syn. Cistus algarvensis is a species of flowering plant in the family Cistaceae native to southern Portugal and southern Spain. It is an erect evergreen shrub growing to 60 cm (24 in) tall by 100 cm (3 ft) wide with woolly grey-green leaves and bright yellow flowers in spring. The flowers may have a dark brown blotch at the base of each petal.In cultivation this plant requires a sandy soil and full sun.\n==>\n", "completion": "Plant"} -{"prompt": " Kaala Patthar (English: Black Stone) is a 1979 Indian Bollywood action/drama film. It was produced and directed by Yash Chopra. The story was written by Salim-Javed. This film is the fourth collaboration between Amitabh Bachchan Shashi Kapoor and director Yash Chopra after the hugely successful Deewaar (1975) Kabhie Kabhie (1976) and Trishul (1978). However this film did average business at the box office. It was nominated for Filmfare awards.\n==>\n", "completion": "Film"} -{"prompt": " Martin G.S. Mansergh (born 31 December 1946) is a former Irish Fianna F\u00e1il politician and historian. He was a Teachta D\u00e1la (TD) for the Tipperary South constituency from 2007 until 2011. He was previously a Senator from 2002 to 2007. He played a leading role in formulating Fianna F\u00e1il policy on Northern Ireland.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Shriniwas Ganesh Sardesai (1907-1996) popularly known as S.G. Sardesai was an Indian freedom fighter from Maharashtra and one of the great communist leaders produced by the communist movement in India. He is author of the book Progress and conservatism in ancient India famous for his profound theoretical analysis. He was the Central Executive Committee of pre-split Communist Party of India during the Indo-china conflict.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " USS Tuluran (AG-46) \u2013 also known as USS Lake Superior (ID-2995) \u2013 was a commercial cargo ship acquired by the U.S. Navy for service during both World War I when she was known as USS Lake Superior and also during World War II when she was known as USS Tuluran.\n==>\n", "completion": "MeanOfTransportation"} -{"prompt": " The American Journal of Gastroenterology is a peer-reviewed medical journal published for the American College of Gastroenterology by the Nature Publishing Group.\n==>\n", "completion": "WrittenWork"} -{"prompt": " William Lindsay (September 4 1835 \u2013 October 15 1909) was a Democratic U.S. Senator from Kentucky from 1893 to 1901.Born near Lexington Virginia Lindsay attended the common schools and settled in Clinton Kentucky in 1854. There he taught school and studied law. He was admitted to the bar and commenced practice in Clinton in 1858.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Brian Schroeder (a.k.a. Pushead) is an artist record label owner and writer within the hardcore punk and heavy metal field. He has created artwork for many bands artists and athletes including Metallica The Misfits Dr. Dre Travis Barker Craig Johnson and Kool Keith. He has designed many record covers T-shirts skateboards and a pair of Nike SB Dunks. His record label Pusmort Records has released albums by Negative Gain Poison Idea and Final Conflict.\n==>\n", "completion": "Artist"} -{"prompt": " Panicum anceps is a species of grass known by the common name beaked panicgrass. It is native to the southeastern United States where it occurs as far north as New Jersey and as far west as Kansas and Texas.This species is a rhizomatous perennial grass with stems growing up to 1.3 meters tall. The leaves have erect blades up to half a meter tall. The inflorescence is a panicle up to 40 centimeters long bearing pale green or yellowish spikelets. The grass produces an abundance of seed.\n==>\n", "completion": "Plant"} -{"prompt": " Shukan ST is a weekly newspaper published by The Japan Times for learners of English language. It is originally titled as Student Times but changed to Shukan ST since a significant portion of its readers are not students. It has articles on news movie lifestyle in English-speaking countries opinions and other kinds attracting learners of English and helping them with notes on terms.\n==>\n", "completion": "Company"} -{"prompt": " The Tiger Hotel is a hotel in Columbia Missouri. Built as a hotel in 1928 the building later housed a retirement home and banquet center. In 2012 the building was fully restored and reopened as a boutique hotel. It was listed on the National Register of Historic Places in 1980.\n==>\n", "completion": "Building"} -{"prompt": " Emi Motoi (\u672c\u4e95 \u3048\u307f Motoi Emi born October 11 in Kanagawa) is a Japanese voice actress.\n==>\n", "completion": "Artist"} -{"prompt": " The Hudson River is a 49.5-mile-long (79.7 km) tributary of the Broad River in the U.S. state of Georgia. Via the Broad River it is part of the Savannah River watershed.The headwaters are in Banks County near the city of Homer. Grove Creek feeds into the Hudson near the Franklin County line. The river then constitutes most of the southern border of Franklin County separating it from Madison County.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " This article details Car Nos. 10\u201313 of the Manx Electric Railway on the Isle of Man.This was the third batch of motorcars delivered to the railway in 1895 at the same time as the cars for the new Snaefell Mountain Railway were delivered. They were constructed to a very similar design to those provided for the mountain line.\n==>\n", "completion": "MeanOfTransportation"} -{"prompt": " Catharanthus roseus commonly known as the Madagascar rosy periwinkle is a species of Catharanthus native and endemic to Madagascar. Other English names occasionally used include Cape periwinkle rose periwinkle rosy periwinkle and old-maid.\n==>\n", "completion": "Plant"} -{"prompt": " Thapanzeik is a village in Homalin Township Hkamti District in the Sagaing Region of northwestern Burma.\n==>\n", "completion": "Village"} -{"prompt": " USS Spiegel Grove (LSD-32) was a Thomaston-class dock landing ship of the United States Navy. She was named for Spiegel Grove the home and estate in Fremont Ohio of Rutherford B. Hayes the 19th President of the United States.\n==>\n", "completion": "MeanOfTransportation"} -{"prompt": " Acmella is a genus of thirty species of plants in the aster family Asteraceae. It is native to the Americas and has been introduced to Asia Africa the Pacific islands and Australia.One familiar species is Acmella oleracea which has been widely cultivated for centuries. It is used for food and medicine and as an insecticide and an ornamental plant.\n==>\n", "completion": "Plant"} -{"prompt": " Mirbelia is a plant genus belonging to the Fabaceae family. It is endemic to Australia occurring in every mainland state except South Australia.\n==>\n", "completion": "Plant"} -{"prompt": " Nigma puella is a species of spider belonging to the family Dictynidae. It is found in Europe Azores Madeira Canary Islands and parts of North Africa.Like most members of the family this is a small spider but the female is striking with a light green abdomen marked with a bold maroon blotch and a variable amount of barring in the same colour. The male is reddish-brown. This species makes a horizontal web over the top surface of a leaf.\n==>\n", "completion": "Animal"} -{"prompt": " The Madrisa (or Madrisahorn) is a mountain in the R\u00e4tikon mountain range overlooking Klosters in the Swiss canton of Graub\u00fcnden. Its summit (2826 metres) is located near the Austrian border.The Madrisa is constituted by several secondary summits notably the Gargeller Madrisa (2770 metres) overlooking Gargellen in Austria.Ski lifts up to 2600 metres are located on the Klosters side.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " Temporary Temple is a live album by Psychic TV. The album was recorded on July 28 1984 in London and released on 12 vinyl. It was later coupled with another concert and released on CD as Temporary Temple & Atonal.\n==>\n", "completion": "Album"} -{"prompt": " La hija de Juan Sim\u00f3n (Juan Sim\u00f3n's Daughter) is a musical play by Nemesio M. Sobrevila which has been made into two Spanish films. It is also the name of the title track and the song has been recorded by numerous artists such as Leonardo Favio.The first film directed by Jos\u00e9 Luis S\u00e1enz de Heredia was released in 1935 and starred Angelillo Pilar Mu\u00f1oz and Manuel Arb\u00f3. Luis Bu\u00f1uel was the executive producer for Film\u00f3fono and had a small role as an actor.\n==>\n", "completion": "Film"} -{"prompt": " Book Of Matches is a poetry book written by Simon Armitage first published in 1993 by Faber and Faber. Several poems featured in the book are studied as part of the GCSE English Literature examination in the UK.The book is written in three sections the first (Book of Matches) containing 30 short sonnets. Each is meant to be read within 20 seconds the amount of time it would take for a match to be lit and burn out.\n==>\n", "completion": "WrittenWork"} -{"prompt": " The Last Supper is the fourth album released by American stand-up comedian Jim Gaffigan. It focuses largely on his love of food.\n==>\n", "completion": "Album"} -{"prompt": " The Miami Center is a skyscraper in downtown Miami Florida. Although Miami Center is not the city's tallest building it is a symbol of early downtown. Built in 1983 it is older compared with most of the taller buildings in Miami which have been built in the last decade. In addition the Miami Center is immediately adjacent to Bayfront Park and is unobstructed when looking at the skyline from Miami Beach to the east. The building is 484 ft (148 m) tall and has 34 floors.\n==>\n", "completion": "Building"} -{"prompt": " Duboisia hopwoodii is a shrub native to the arid interior region of Australia. Common names include pituri pitchuri thornapple or pitcheri. It has an erect habit usually growing to between 1 and 3 metres in height and has long narrow leaves. Flowers are white and bell-shaped with violet-striped throats. These appear between June and November in the species native range followed by purple-black rounded berries which are 3 to 6 mm in diameter.\n==>\n", "completion": "Plant"} -{"prompt": " Jelenin svet (Jelena's World) is a 2008 independent documentary film written and directed by Tanja Brzakovi\u0107 about former World No. 1 female tennis player Jelena Jankovi\u0107.\n==>\n", "completion": "Film"} -{"prompt": " Jay Cashman Inc. is an American heavy-construction company based in Quincy Massachusetts with satellite offices in Boston Jupiter Florida and Staten Island New York. As of 2006 the company has about 1000 employees. The company was one of the major contractors on the Boston's Central Artery/Tunnel Project. In 2004 Jay Cashman Inc.\n==>\n", "completion": "Company"} -{"prompt": " Hashemanli (Persian: \u0647\u0627\u0634\u0645\u0646\u0644\u064a\u200e also Romanized as H\u0101shemanl\u012b; also known as H\u0101shem El\u00e1) is a village in Jafarbay-ye Jonubi Rural District in the Central District of Torkaman County Golestan Province Iran. At the 2006 census its population was 135 in 27 families.\n==>\n", "completion": "Village"} -{"prompt": " Rani Kasula Rangamma is a Telugu film starring Chiranjeevi.\n==>\n", "completion": "Film"} -{"prompt": " The 20/20 Experience \u2013 The Complete Experience is a compilation album by American singer-songwriter Justin Timberlake. It was released on September 27 2013 by RCA Records.\n==>\n", "completion": "Album"} -{"prompt": " R.C. Bigelow Inc better known as the Bigelow Tea Company is an American tea company based in Fairfield Connecticut. The company was founded by Ruth C. Bigelow in the late 1940s based on a recipe she marketed as Constant Comment tea. Bigelow is still a 100% family-owned business that markets over 50 varieties of tea including black and green as well as herbal teas all of which are still blended in Fairfield. They also own America's only tea plantation in Charleston South Carolina.\n==>\n", "completion": "Company"} -{"prompt": " Thomas Eyre(fl. 1890s) was a footballer who made 65 appearances in the Football League playing for Lincoln City. He played at left back. Either side of Lincoln he played for Ashfield and Hamilton Academical in Scotland.\n==>\n", "completion": "Athlete"} -{"prompt": " Malleable Iron Range Company was a company that existed from 1896 to 1985 and primarily produced kitchen ranges made of malleable iron but also produced a variety of other related products. The company's primary trademark was 'Monarch' and was colloquially often referred to as the Monarch Company or just Monarch.\n==>\n", "completion": "Company"} -{"prompt": " The Chiltern School is a coeducational special school located over two sites in Dunstable and Houghton Regis in Bedfordshire England. The school accepts pupils from all over the Central Bedfordshire area.The school was formed in 2012 from the merger of Glenwood School in Dunstable and Hillcrest School in Houghton Regis.\n==>\n", "completion": "EducationalInstitution"} -{"prompt": " Kim Dae-Eun (born September 17 1984) is a South Korean gymnast. He is the 2004 Olympic All-around silver medalist. He won the gold medal on the parallel bars at the 2007 World Artistic Gymnastics Championships.Kim was part of the South Korean team that won the bronze medal in the team event at the 2006 Asian Games.\n==>\n", "completion": "Athlete"} -{"prompt": " Arayik Vladimirovich Harutyunyan (Armenian: \u0531\u0580\u0561\u0575\u056b\u056f \u0540\u0561\u0580\u0578\u0582\u0569\u0575\u0578\u0582\u0576\u0575\u0561\u0576 Russian: \u0410\u0440\u0430\u0438\u043a \u0410\u0440\u0443\u0442\u044e\u043d\u044f\u043d) (born 14 December 1973) is the current Prime Minister of the Nagorno-Karabakh Republic. He was suggested by the President of Nagorno-Karabakh Bako Sahakyan and was unanimously approved by the Parliament of Karabakh on 14 September 2007 by 32 out of 32 present parliamentarians.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Shelton Hank Williams also known as Hank Williams III and Hank 3 (born December 12 1972) is an American musician singer and multi-instrumentalist including guitar bass drums banjo and vocals. In addition to his honky tonk recordings Williams' style alternates between country punk and metal.\n==>\n", "completion": "Artist"} -{"prompt": " Helicella orzai is a species of air-breathing land snails terrestrial pulmonate gastropod mollusks in the family Hygromiidae the hairy snails and their allies. This species is endemic to Spain.\n==>\n", "completion": "Animal"} -{"prompt": " Gro\u00dfe Schmalenau is a river of North Rhine-Westphalia Germany.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " The Tupolev ANT-29 (military designation DIP \u2013 Dvukhmotorny istrebitel pushechny twin-engined cannon fighter) was a 1930s twin-engined cannon-armed fighter designed by Alexander Arkhangelsky and built by Tupolev.Design work started in 1932 on a twin-engined aircraft capable of carrying two APK-100 cannons. The resulting design was the ANT-29 and it first flew in February 1935. A monoplane with a tall and narrow fuselage and powered by two Hispano-Suiza 12Ybrs engines.\n==>\n", "completion": "MeanOfTransportation"} -{"prompt": " Charles Corm (1894-1963) was a Lebanese writer businessman and philanthropist. He is considered to be the leader of the Phoenicianism movement in Lebanon which ignited a surge of nationalism that led to Lebanon's independence. In a country torn by sectarian conflicts Corm's intention was to find a common root shared by all Lebanese beyond their religious beliefs (the Phoenicians were pagans).\n==>\n", "completion": "Artist"} -{"prompt": " Joseph Hubert Ruetz (October 21 1916 \u2013 January 2 2003) was a professional football player in the All-America Football Conference for the Chicago Rockets in 1946 and 1948. Prior to that he played at the collegiate level while attending the University of Notre Dame. He played guard for the Irish with the exception of playing one season at quarterback. In 1938 he graduated from Notre Dame with cum laude honors.\n==>\n", "completion": "Athlete"} -{"prompt": " The Reef House is a historic house located at 411 S. Poplar St. in Carbondale Illinois. William A. Reef built the house for his family circa 1892. The Queen Anne-style cottage may have been designed by local carpenter A. M. Etherton though records of its designer do not exist. The house features fishscale shingle siding on its second floor and clapboard siding on its first; the clapboard siding is adorned with stickwork.\n==>\n", "completion": "Building"} -{"prompt": " MAKO Surgical Corp. (Stryker Medical) is a publicly traded medical device company based in Florida. On September 25 2013 the Board of Directors of Mako Surgical accepted a deal to merge with Stryker Medical for $1.65B subject to shareholder approval.\n==>\n", "completion": "Company"} -{"prompt": " Pop Carn is a 2003 Indian Tamil film written and directed by actor-cum-director Nassar and starring Mohanlal and Simran Bagga in lead roles and introducing newcomers Kunal Shah and Jyothi Nawal. The film which had music scored by Yuvan Shankar Raja was released on 30 January 2003 but flopped at the box office. Nonetheless the film was dubbed into Malayalam and released in 2007 under the same name.\n==>\n", "completion": "Film"} -{"prompt": " USNS Mount Baker (T-AE-34) is the seventh of eight Kilauea-class ammunition ships to serve with the Military Sealift Command. She is the second U.S. Navy ship to bear the name and is named for Mount Baker a 10781-foot volcano in the Cascade Range of Washington. Ammunition ships operated by Military Sealift Command provide logistic support to US Navy ships at sea.Mount Baker was built by Ingalls Shipbuilding Pascagoula Mississippi.\n==>\n", "completion": "MeanOfTransportation"} -{"prompt": " Dansere is an album by Jan Garbarek. The album was recorded in November 1975 and features the Bobo Stenson Quartet.\n==>\n", "completion": "Album"} -{"prompt": " Divraz (Persian: \u062f\u064a\u0648\u0631\u0632\u200e also Romanized as D\u012bvraz) is a village in Bala Khiyaban-e Litkuh Rural District in the Central District of Amol County Mazandaran Province Iran. At the 2006 census its population was 393 in 95 families.\n==>\n", "completion": "Village"} -{"prompt": " The D\u0103ih\u0103\u021ba\u0219u River is a tributary of the Dumbr\u0103vanu River in Romania.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " Zeisters also known as Fat Guy Goes Nutzoid is a 1986 comedy film produced by Troma Entertainment. Troma was originally set to title the film Fat Boy Goes Nutzoid but at the request of the lawyers of the hip-hop group The Fat Boys it was changed to Fat Guy.\n==>\n", "completion": "Film"} -{"prompt": " Paul Gobeil (born March 1 1942 in Saint-R\u00e9mi-de-Tingwick Quebec) is a former Canadian politician and businessman.From 1985 to 1989 Mr. Gobeil was a Liberal member of the National Assembly for the riding of Verdun and served as Minister assigned to Administration President of the Treasury Board and as Minister of International Affairs for the Government of Quebec.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Ruff Ryders: Past Present Future is the fifth compilation album from American hip hop record label Ruff Ryders Entertainment released on November 21 2011.\n==>\n", "completion": "Album"} -{"prompt": " Ridi Viharaya (Sinhala: \u0dbb\u0dd2\u0daf\u0dd3 \u0dc0\u0dd2\u0dc4\u0dcf\u0dbb\u0dba) or Silver Temple is a 2nd-century BCE Theravada Buddhist temple in the village of Ridigama Sri Lanka. Built during the reign of Dutthagamani of Anuradhapura the temple is considered as the place where the silver ore which provided silver to complete Ruwanwelisaya; one of the largest stupa in Sri Lanka was discovered.\n==>\n", "completion": "Building"} -{"prompt": " Grand Canyon Preparatory Academy is a public charter college preparatory school in Tempe Arizona.\n==>\n", "completion": "EducationalInstitution"} -{"prompt": " Aricoceras is an extinct genus of the Adrianitidae family. They are an extinct group of ammonoid which are shelled cephalopods related to squids belemnites octopuses and cuttlefish and more distantly to the nautiloids.\n==>\n", "completion": "Animal"} -{"prompt": " Blackburn High School is a public secondary school for girls and boys in years 7 to 12 in Blackburn a suburb of Melbourne Victoria Australia. Blackburn High School is an outstanding secondary school for aspiring young men and women. It aims to educate tomorrow's minds today. Started in 1956 the school has a proud tradition of academic excellence and exceptional music achievement.The school is nationally recognised as a leading educational institution for music education.\n==>\n", "completion": "EducationalInstitution"} -{"prompt": " Chris Nieratko (born February 19 1976) is an American humorist and author. Nieratko is a past editor of Big Brother Magazine and currently reviews pornographic films for Vice magazine as well as being the author of the related Skinema book. He also appeared on MTV's Jackass.\n==>\n", "completion": "Artist"} -{"prompt": " Warlock is a 1959 film released by Twentieth Century Fox and shot in DeLuxe Color and CinemaScope. It is a Western adapted from the novel by Oakley Hall (screenplay written by Robert Alan Aurthur).\n==>\n", "completion": "Film"} -{"prompt": " Sieniawa [\u0255e\u02c8\u0272ava] is a village in the administrative district of Gmina Raba Wy\u017cna within Nowy Targ County Lesser Poland Voivodeship in southern Poland. It lies approximately 5 kilometres (3 mi) south-east of Raba Wy\u017cna 10 km (6 mi) north-west of Nowy Targ and 59 km (37 mi) south of the regional capital Krak\u00f3w.The village has a population of 1900.\n==>\n", "completion": "Village"} -{"prompt": " Michael Adam (born 9 December 1984) is a German politician. He has been District Administrator (Landrat) of Regen since 2011.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Thunderbird High School is a public high school located in northwestern Phoenix Arizona. The school is a part of the Glendale Union High School District.\n==>\n", "completion": "EducationalInstitution"} -{"prompt": " Nayef Al Khater (born May 10 1978) is a Qatari football player. He currently plays for Al Wakrah as a defender.\n==>\n", "completion": "Athlete"} -{"prompt": " Black Cobra Woman (Italian: Eva nera) also known as Black Cobra is an Italian 1976 exploitation movie written and directed by Joe D'Amato.\n==>\n", "completion": "Film"} -{"prompt": " Joe Cuba a.k.a Sonny (April 22 1931 \u2013 February 15 2009) was a musician of Puerto Rican descent who was known as the Father of Latin Boogaloo.\n==>\n", "completion": "Artist"} -{"prompt": " Jacob LeBlanc (born February 2 1981 in Auburn California) is an American retired professional soccer player.\n==>\n", "completion": "Athlete"} -{"prompt": " Kevin B. Kamenetz is the 12th and current County Executive of Baltimore County Maryland serving since 2010. He is a member of the Democratic Party. He previously served as a four-term County Councilman representing the Second District of Baltimore County.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Thomas Frederick Fred Peart Baron Peart PC (30 April 1914 \u2013 26 August 1988) was a British Labour politician who served in the Labour governments of the 1960s and 1970s and was a candidate for Deputy Leader of the Party.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Grand Lake is a large lake in the interior of Newfoundland of the Canadian province of Newfoundland and Labrador. It has an area of 534 km\u00b2 making it the largest lake on Newfoundland. Consequently it is one of if not the deepest.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " A Colossal Failure of Common Sense: The Inside Story of the Collapse of Lehman Brothers is a 2009 non-fiction book written by Lawrence G. McDonald and Patrick Robinson which chronicles the events surrounding the bankruptcy of Lehman Brothers in the context of the financial crisis of 2007\u20132010 and the subprime mortgage crisis.\n==>\n", "completion": "WrittenWork"} -{"prompt": " Thatching (31 May 1975 \u2013 1999) was an Irish Thoroughbred racehorse and sire. The horse's early career was delayed and disrupted by injury and he did not show his best form until switched to sprinting distances in the spring of 1979 when he won the Duke of York Stakes. He improved further when equipped with blinkers that summer recording impressive victories in both the Cork and Orrery Stakes and the July Cup.\n==>\n", "completion": "Animal"} -{"prompt": " Ya\u015far Kurt (Armenian: \u0545\u0561\u0577\u0561\u0580 \u053f\u0578\u0582\u0580\u0569 b.August 16 1968 in Istanbul Turkey) is a Turkish-Armenian rock artist.\n==>\n", "completion": "Artist"} -{"prompt": " Then and Now is a historical novel by W. Somerset Maugham. Set in Florence Italy during the Renaissance the story focuses on three months in the life of Niccolo Machiavelli the Florentine politician diplomat philosopher and writer in the early years of the 16th century. The book was first published by Heinemann in 1946.\n==>\n", "completion": "WrittenWork"} -{"prompt": " Abdollah Masud-e Sofla (Persian: \u0639\u0628\u062f\u0627\u0644\u0647 \u0645\u0633\u0639\u0648\u062f\u0633\u0641\u0644\u064a\u200e also Romanized as \u2018Abdoll\u0101h Mas\u2018\u016bd-e Sofl\u00e1; also known as Abdollah Mas\u2019ood \u2018Abdoll\u0101h Mas\u2018\u016bd and Abdull\u0101h Mas\u016bd) is a village in Hesar-e Valiyeasr Rural District Avaj District Buin Zahra County Qazvin Province Iran. At the 2006 census its population was 72 in 15 families.\n==>\n", "completion": "Village"} -{"prompt": " Springhill High School (SHS) is a secondary school in Springhill Nova Scotia Canada. SHS is part of the Chignecto-Central Regional School Board and is the only high school in the town of Springhill. The school is home to many sports teams and clubs. These include: basketball soccer badminton track and field softball Students Against Destructive Decisions drama club homework club and book club.\n==>\n", "completion": "EducationalInstitution"} -{"prompt": " Charniele L. Herring (/\u0283\u0251r\u02c8n\u025bl \u02c8h\u025br\u026a\u014b/ shar-NEL HERR-ing; born September 25 1969) is an American politician. She has served in the Virginia House of Delegates since 2009 representing the 46th district made up the city of Alexandria and part of Fairfax County near Washington D.C. Herring is a member of the Democratic Party. She has been the House minority whip since 2012 and in December 2012 she was the first African-American to be elected chair of the Democratic Party of Virginia.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Symmoca dodecatella is a moth of the Symmocidae family. It is found in Portugal and Spain.The wingspan is about 18\u201319 mm. The forewings are grey sprinkled with black mainly along the margin. The hindwings are grey.\n==>\n", "completion": "Animal"} -{"prompt": " Ali Abbasov Mammad oglu (Azerbaijani: \u018fli Abbasov M\u0259mm\u0259d o\u011flu) (born 1953 in Azerbaijan) is the current Minister of Communications and Information Technologies of the Republic of Azerbaijan.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Worlds Beyond was an American digest magazine of science fiction and fantasy fiction in 1950 and 1951. The magazine only issued three monthly issues from December 1950 to February 1951 but is notable for having printed stories by Cyril M. Kornbluth Jack Vance Mack Reynolds Graham Greene John Christopher Lester del Rey Judith Merril and others.Worlds Beyond was published by Hillman Periodicals and was edited by Damon Knight.\n==>\n", "completion": "Company"} -{"prompt": " The Daily News Journal commonly abbreviated to DNJ is a newspaper serving Murfreesboro Tennessee Rutherford County and surrounding communities. Published in Murfreesboro it serves as the primary local newspaper with competition from The Murfreesboro Post and other publications. The newspaper is not in competition with The Tennessean of Nashville as both are owned by Gannett Company.The roots the DNJ date back to 1849 and the founding of Murfreesboro News.\n==>\n", "completion": "WrittenWork"} -{"prompt": " Echinocereus fendleri is a species of cactus known by the common names pinkflower hedgehog cactus and Fendler's hedgehog cactus. It grows in deserts and woodlands in the Southwestern United States and Northeastern Mexico. It is most common in New Mexico.The taxonomy of the species is uncertain with authors recognizing up to eight varieties.\n==>\n", "completion": "Plant"} -{"prompt": " Michael F. Kitt Snr (13 September 1914 \u2013 24 December 1974) was an Irish Fianna F\u00e1il politician and long-serving Teachta D\u00e1la (TD).He was elected to D\u00e1il \u00c9ireann for the first time at the 1948 general election for the Galway North constituency but lost his seat at the 1951 general election and failed to be elected again at the 1954 general election.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Epidendrum mancum is an epiphytic orchid that grows in the tropical low elfin cloud forests of Ecuador and Amazonas Peru at altitudes of 2\u20143 km .\n==>\n", "completion": "Plant"} -{"prompt": " Salempur Masanda is a village in Jalandhar District near the Jalandhar Cantonment in Punjab India.\n==>\n", "completion": "Village"} -{"prompt": " Yaleh Gonbad (Persian: \u064a\u0644\u0647 \u06af\u0646\u0628\u062f\u200e; also known as Em\u0101mz\u0101deh Imamzade-Ele-Geumbez and Im\u0101mz\u0101deh) is a village in Ilat-e Qaqazan-e Gharbi Rural District Kuhin District Qazvin County Qazvin Province Iran. At the 2006 census its population was 429 in 105 families.\n==>\n", "completion": "Village"} -{"prompt": " Popeyes Louisiana Kitchen is an American chain of fried chicken fast food restaurants founded in 1972 in New Orleans Louisiana. Often referred to as Popeyes and sometimes as Popeyes Chicken & Biscuits or Popeyes Chicken & Seafood[citation needed] it was acquired by Sandy Springs Georgia-based AFC Enterprises originally America's Favorite Chicken Company in 1993.\n==>\n", "completion": "Company"} -{"prompt": " The White Umfolozi River originates just south of Vryheid KwaZulu-Natal South Africa and joins the Black Umfolozi River at 28\u00b020\u203258\u2033S 31\u00b058\u203246\u2033E to form the Umfolozi River before it flows east towards the Indian Ocean.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " The Albatros L 74 was a two-seated German training biplane produced by Albatros Flugzeugwerke. Only two were produced.\n==>\n", "completion": "MeanOfTransportation"} -{"prompt": " The University of Nevada School of Medicine is an academic division of the University of Nevada Reno and grants the Doctor of Medicine (MD) degree. The School of Medicine was founded in 1969 as the first medical school in the state of Nevada. More than 1500 MDs have graduated from the School of Medicine. The pre-clinical campus is located in Reno but the third and fourth years can be spent in hospitals and clinics throughout Nevada.\n==>\n", "completion": "EducationalInstitution"} -{"prompt": " Leon Kroll (December 6 1884 \u2013 October 25 1974) was an American painter and lithographer. Known as a figurative artist Life Magazine described him as the dean of U.S. nude painters yet he was an exceptional landscape painter and also produced an exceptional body of still life compositions.Born into a musical family on lower Second Avenue in New York City Kroll's father was a violinist and his cousin was William Kroll.\n==>\n", "completion": "Artist"} -{"prompt": " Michael E. DeBakey High School for Health Professions at Qatar (DHSHP@Q in short) is a private international middle and secondary school in Doha Qatar. The school is a branch campus of Michael E. DeBakey High School for Health Professions of Houston Texas United States. Charlesetta Deason is the CEO and President.Named after Michael E. DeBakey the school opened in September 2008 with grades 8 through 10 with 100 students per grade; the school will ultimately cover grades 7-12.\n==>\n", "completion": "EducationalInstitution"} -{"prompt": " The Richleighs of Tantamount is a children\u2019s historical novel written by British author Barbara Willard. It was originally published in the United Kingdom in 1966 by the publishers Constable before being published in the United States by Harcourt Brace & World in June 1967. C. Walter Hodges drew the line illustrations and painted the cover portrait for the original edition.\n==>\n", "completion": "WrittenWork"} -{"prompt": " Ennea is a genus of air-breathing land snails terrestrial pulmonate gastropod mollusks in the family Streptaxidae.Ennea is the type genus of the subfamily Enneinae.\n==>\n", "completion": "Animal"} -{"prompt": " Come Live with Me is a 1941 American romantic comedy film produced and directed by Clarence Brown and starring James Stewart and Hedy Lamarr. Based on a story by Virginia Van Upp the film is about a beautiful Viennese refugee seeking United States citizenship who arranges a marriage of convenience with a struggling writer.\n==>\n", "completion": "Film"} -{"prompt": " St. Thomas Episcopal Church is a parish church in the Episcopal Diocese of Iowa. The church is located in Sioux City Iowa United States at 1200 Douglas Street. The church building is listed on the National Register of Historic Places.\n==>\n", "completion": "Building"} -{"prompt": " Nuno Daniel Costeira Valente (born 22 November 1991 in Ada\u00fafe - Braga ) is a Portuguese footballer who plays for Vizela on loan from S.C. Braga as a midfielder.\n==>\n", "completion": "Athlete"} -{"prompt": " Jaagoo (Bengali: \u099c\u09be\u0997\u09cb) is a Bangladeshi sports based romantic Movies. Its writer and director Khijir Hayat Khan. Adnan Karim sponsored youth football game built this film was released in 2010. The film is produced by Sharjeel Karim and Adnan Karim and directed by Khijir Hayat Khan who has written the story screenplay and dialogues of the film. The film features Ferdous Ahmed and Afsana Ara Bindu in lead roles and with supporting Arefin Shuvo Tariq Anam Ronok Hasaan and many more.\n==>\n", "completion": "Film"} -{"prompt": " John Edward Hatton AO (born 29 May 1933) is former Australian politician and an National Trust of Australia nominated Australian Living Treasure. He was the independent member of the Legislative Assembly of the New South Wales parliament for the seat of South Coast from 1973 to 1995. Notably the allegations about police corruption Hatton raised in Parliament resulted in the Wood Royal Commission. He is currently a social activist in his local community.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Trichoptilus subtilis is a moth of the Pterophoridae family that is known from South Africa.\n==>\n", "completion": "Animal"} -{"prompt": " Sin\u00e9ad Madden (born in Galway Ireland) is an Irish singer-songwriter and fiddle player best known as a member of the Moya Brennan band. She also teaches at Waltons New School of Music in Dublin.\n==>\n", "completion": "Artist"} -{"prompt": " Philip Sprint is a German footballer who currently plays for Hertha BSC.Sprint made his professional debut for Hertha BSC on 12 August 2012 in a 2. Bundesliga match against FSV Frankfurt coming on in the 50th minute for Marvin Knoll after starting goalkeeper Sascha Burchert had been sent off.\n==>\n", "completion": "Athlete"} -{"prompt": " River Roads Mall was an enclosed shopping mall located in the city of Jennings a suburb of St. Louis Missouri United States. Opened in 1962 as one of the nation's first shopping malls the mall declined in the 1990s becoming a dead mall and eventually being shuttered in 1995. Demolition of the long-vacant mall began in 2006.\n==>\n", "completion": "Building"} -{"prompt": " The Brown-patched Kangaroo lizard (Otocryptis wiegmanni) also called Wiegmann's Agama or Sri Lankan Kangaroo Lizard is a small ground dwelling agamid lizard endemic to the wet zone forests and lower mountain forests (up to 1300 metres) of Sri Lanka. It is commonly seen in the leaf litter of shady rain forests. When perceiving danger it spurts away quickly on its large hind legs and might eventually climb up a sapling or tree.\n==>\n", "completion": "Animal"} -{"prompt": " Shiho Kawaragi (\u6cb3\u539f\u6728 \u5fd7\u7a42 Kawaragi Shiho born April 29 1976 in Tokyo) is a Japanese voice actress who works for Kenyu-Office. When voicing adult games and hentai OVAs she is also known as Kaname Yuzuki (\u67da\u6728\u304b\u306a\u3081 Yuzuki Kaname) She is currently married since March 2012.\n==>\n", "completion": "Artist"} -{"prompt": " Down in the Shacks Where the Satellite Dishes Grow is the second album by the Judybats released in 1992.\n==>\n", "completion": "Album"} -{"prompt": " Turn of Faith is a 2001 film directed by Charles Jarrott. It stars Ray Mancini and Mia Sara.\n==>\n", "completion": "Film"} -{"prompt": " Frederick William Seward (July 8 1830 \u2013 April 25 1915) was the Assistant Secretary of State during the American Civil War serving in Abraham Lincoln's administration as well as under Andrew Johnson during Reconstruction and for over two years under Rutherford B. Hayes.\n==>\n", "completion": "OfficeHolder"} -{"prompt": " Ivoprop Corporation founded in 1984 by Ivo Zdarsky is an American manufacturer of composite propellers for homebuilt and ultralight aircraft as well as airboats. The company headquarters is located in Bellflower California.Zdarsky started the company after carving his own propeller for a homebuilt ultralight trike that he flew from Cold War Czechoslovakia over the Iron Curtain to Vienna in 1984.\n==>\n", "completion": "Company"} -{"prompt": " Wave Broadband is a provider of residential business and enterprise class cable TV broadband internet and telephone services on the West Coast currently serving about 400000 customers within communities in western Washington state Oregon Sacramento California and the San Francisco Bay Area. Wave Broadband provides services via their fiber-optic network and uses Northwest Open Access Network as the backbone for most of their service areas in Washington.\n==>\n", "completion": "Company"} -{"prompt": " Andie Tong is a comic book artist known for his work on books such as Spectacular Spider-Man UK The Batman Strikes! and Tangent: Superman's Reign.\n==>\n", "completion": "Artist"} -{"prompt": " Merdani is a village in the municipality of Busova\u010da Bosnia and Herzegovina.\n==>\n", "completion": "Village"} -{"prompt": " Kamam (Persian: \u0643\u0627\u0645\u0645\u200e also Romanized as K\u0101mam) is a village in Mangur-e Sharqi Rural District Khalifan District Mahabad County West Azerbaijan Province Iran. At the 2006 census its population was 98 in 16 families.\n==>\n", "completion": "Village"} -{"prompt": " Ficus greiffiana is a species of plant in the Moraceae family. It is found in Argentina Brazil Colombia and Guyana.\n==>\n", "completion": "Plant"} -{"prompt": " Toni Amboaje is a Spanish singer who currently works for metal band Sauze which formed on early 2008.\n==>\n", "completion": "Artist"} -{"prompt": " Mount Whittier is a mountain in Carroll County New Hampshire in the northern Ossipee Mountains. Named after John Greenleaf Whittier the peak is not to be confused with nearby Nickerson Mountain which was once known as Mount Whittier.There are no hiking trails on Mount Whittier. There was once a CCC alpine ski trail on the northern face.\n==>\n", "completion": "NaturalPlace"} -{"prompt": " El Rompe Discoteka: The Mix Album is a 2007 album by Hector El Father.\n==>\n", "completion": "Album"} -{"prompt": " e-Spirit is a commercial software company that develops and markets the FirstSpirit CMS Web content management system. The company was founded in 1999 in Dortmund Germany and established a US presence in 2011. The company's FirstSpirit CMS is a Java-based offering now in its fifth major release.[citation needed]\n==>\n", "completion": "Company"} -{"prompt": " The Valley is the first novel by Barry Pilton published in 2005 by Bloomsbury. It is a humorous account of the effect of outsiders on the rural status quo in a fictional mid-Wales valley during the 1980s and is being adapted for television.\n==>\n", "completion": "WrittenWork"} -{"prompt": " Sema Group plc was an Anglo-French IT services company. It was listed on the London Stock Exchange and was a constituent of the FTSE 100 Index but was acquired by Schlumberger in 2001.\n==>\n", "completion": "Company"} -{"prompt": " Bent Hansen (born 1954) is a retired Danish ice hockey forward. He played for 18 years in Denmark for the R\u00f8dovre SIK and KSF. He also competed for the Danish national team. His son Jannik Hansen also played for the R\u00f8dovre team and was drafted into the NHL by the Vancouver Canucks in 2004. During his hockey career Hansen also worked as a carpenter.\n==>\n", "completion": "Athlete"} -{"prompt": " Behind the Sun is a 2004 album by Dive.\n==>\n", "completion": "Album"} -{"prompt": " Mungaru Male (English: Pre Monsoon Rain) is a 2006 Kannada language movie directed by Yograj Bhat and produced by E Krishnappa. The film stars Ganesh Pooja Gandhi Anant Nag Padmaja Rao in lead roles.\n==>\n", "completion": "Film"} -{"prompt": " Megachile perihirta commonly known as the Western leafcutting bee is a bee in the genus Megachile. The bee is native to western North America ranging from Nebraska to Texas and Mexico west to California and north to British Columbia and Alberta and often inhabits meadows and orchards. The bee is black with long whitish-yellow hair more so below the thorax and abdomen. The abdomen however is mostly bare although each segment has scattered whitish hair.\n==>\n", "completion": "Animal"} -{"prompt": " Sukeban Deka The Movie (\u30b9\u30b1\u30d0\u30f3\u5211\u4e8b) is a live action Japanese film that was released in 1987. The movie closely follows a TV and manga series Sukeban Deka written and illustrated by Shinji Wada. The movie stars Yoko Minamino and Yui Asaka who were also in the TV series. The movie was followed by Sukeban Deka II in 1988.\n==>\n", "completion": "Film"} -{"prompt": " The Maple School District is a public school district in Douglas County Wisconsin United States based in Maple Wisconsin.\n==>\n", "completion": "EducationalInstitution"} -{"prompt": " Mount Waverley Secondary College is a public secondary school located in the Melbourne suburb of Mount Waverley. The school consists of roughly 1900 students and is one of the largest in the state.The school consists of two campuses (Junior & Senior) both situated on Stephensons Road in Mount Waverley. The Junior site holds years 7 and 8 with year levels 9 to 12 at the Senior Campus. The campuses are a short walking distance apart.\n==>\n", "completion": "EducationalInstitution"} -{"prompt": " Jon-Paul Roger JP Pietersen (born 12 July 1986 in Stellenbosch South Africa) is a South African rugby union footballer. He generally plays fullback or wing for the Sharks (in the Super Rugby competition) and the Natal Sharks in the Currie Cup. He played in more than 50 tests for the Springboks.\n==>\n", "completion": "Athlete"} -{"prompt": " Deltocolpodes is a genus of beetles in the family Carabidae containing the following species: Deltocolpodes brendelli Morvan 1992 Deltocolpodes championi Morvan 1992 Deltocolpodes duluchus Morvan 1992 Deltocolpodes heinigeri Morvan 1992 Deltocolpodes jalepensis Morvan 1992 Deltocolpodes kirschenhoferi Morvan 1992 Deltocolpodes nepalensis Morvan 1992 Deltocolpodes perreaui Deuve 1985 Deltocolpodes rectangulus Morvan 1992 Deltocolpodes rolex Morvan 1992 Deltocolpodes salpensis Deuve 1985 Deltocolpodes sikkimensis Morvan 1992\u2191\n==>\n", "completion": "Animal"} -{"prompt": " Stanhopea martiana is a species of orchid endemic to southwestern Mexico.\n==>\n", "completion": "Plant"} -{"prompt": " Yawarmayu (Quechua yawar blood mayu river blood river hispanicized spelling Yahuarmayo) is a river in Peru located in the Puno Region Carabaya Province Ayapata District. It originates near the border of the districts Ayapata and Coasa. Its direction is mainly to the northwest where it meets Inambari River as a right affluent. The confluence is north of the village Yawarmayu (Yahuarmayo).\n==>\n", "completion": "NaturalPlace"} -{"prompt": " The Charles Granke House at 406 S. Seventh St. in Hamilton Montana is a historic house that was built in 1906. It includes Colonial Revival and Queen Anne architecture. It was listed on the National Register of Historic Places in 1988. The listing included two contributing buildings.It was built in approximately 1906 by the Anaconda Copper Mining Company as a worker cottage for workers at the sawmill that operated in Hamilton until 1915. Charles W.\n==>\n", "completion": "Building"} -{"prompt": " Passiflora monadelpha is a species of plant in the Passifloraceae family. It is endemic to Ecuador.\n==>\n", "completion": "Plant"} -{"prompt": " Mangifera persiciformis or Peach Mango is a species of plant in the Anacardiaceae family. It is endemic to China.\n==>\n", "completion": "Plant"} diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/dbpedia_samples_prepared_train.jsonl b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/dbpedia_samples_prepared_train.jsonl deleted file mode 100644 index 982293a5448981c80b1955cd989611cb4a707c63..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/dbpedia_samples_prepared_train.jsonl +++ /dev/null @@ -1,160 +0,0 @@ -{"prompt":" Hashemanli (Persian: هاشمنلي‎ also Romanized as Hāshemanlī; also known as Hāshem Elá) is a village in Jafarbay-ye Jonubi Rural District in the Central District of Torkaman County Golestan Province Iran. At the 2006 census its population was 135 in 27 families.\n==>\n","completion":" Village"} -{"prompt":" Lomatium macrocarpum is a perennial flowering plant in the carrot family known by the common names bigseed lomatium biscuit root or even bigseed biscuitroot. It is native to much of western North America where it can be found in various types of habitat including the grasslands of the Great Plains. It is spreading or erect perennial herb growing up to about half a meter long with hairy gray-green herbage.\n==>\n","completion":" Plant"} -{"prompt":" Sardar Vallabhbhai Patel National Memorial is a museum and exhibition centre dedicated to Sardar Vallabhbhai Patel at Moti Shahi Mahal located in Shahibaug Ahmedabad Gujarat. Moti Shahi Mahal was constructed by Mughal emperor Shahjahan between 1618 and 1622. It is surrounded by a garden.\n==>\n","completion":" Building"} -{"prompt":" The Richleighs of Tantamount is a children’s historical novel written by British author Barbara Willard. It was originally published in the United Kingdom in 1966 by the publishers Constable before being published in the United States by Harcourt Brace & World in June 1967. C. Walter Hodges drew the line illustrations and painted the cover portrait for the original edition.\n==>\n","completion":" WrittenWork"} -{"prompt":" Thunderbird High School is a public high school located in northwestern Phoenix Arizona. The school is a part of the Glendale Union High School District.\n==>\n","completion":" EducationalInstitution"} -{"prompt":" Divraz (Persian: ديورز‎ also Romanized as Dīvraz) is a village in Bala Khiyaban-e Litkuh Rural District in the Central District of Amol County Mazandaran Province Iran. At the 2006 census its population was 393 in 95 families.\n==>\n","completion":" Village"} -{"prompt":" Shriniwas Ganesh Sardesai (1907-1996) popularly known as S.G. Sardesai was an Indian freedom fighter from Maharashtra and one of the great communist leaders produced by the communist movement in India. He is author of the book Progress and conservatism in ancient India famous for his profound theoretical analysis. He was the Central Executive Committee of pre-split Communist Party of India during the Indo-china conflict.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Shiho Kawaragi (河原木 志穂 Kawaragi Shiho born April 29 1976 in Tokyo) is a Japanese voice actress who works for Kenyu-Office. When voicing adult games and hentai OVAs she is also known as Kaname Yuzuki (柚木かなめ Yuzuki Kaname) She is currently married since March 2012.\n==>\n","completion":" Artist"} -{"prompt":" Ivoprop Corporation founded in 1984 by Ivo Zdarsky is an American manufacturer of composite propellers for homebuilt and ultralight aircraft as well as airboats. The company headquarters is located in Bellflower California.Zdarsky started the company after carving his own propeller for a homebuilt ultralight trike that he flew from Cold War Czechoslovakia over the Iron Curtain to Vienna in 1984.\n==>\n","completion":" Company"} -{"prompt":" Enrico Perucconi (born 4 January 1925 in Morazzone Varese Italy) was an Italian athlete who competed mainly in the 100 metres.\n==>\n","completion":" Athlete"} -{"prompt":" Halimium ocymoides (basil-leaved rock rose) syn. Cistus algarvensis is a species of flowering plant in the family Cistaceae native to southern Portugal and southern Spain. It is an erect evergreen shrub growing to 60 cm (24 in) tall by 100 cm (3 ft) wide with woolly grey-green leaves and bright yellow flowers in spring. The flowers may have a dark brown blotch at the base of each petal.In cultivation this plant requires a sandy soil and full sun.\n==>\n","completion":" Plant"} -{"prompt":" El Rompe Discoteka: The Mix Album is a 2007 album by Hector El Father.\n==>\n","completion":" Album"} -{"prompt":" Trichoptilus subtilis is a moth of the Pterophoridae family that is known from South Africa.\n==>\n","completion":" Animal"} -{"prompt":" The Hudson River is a 49.5-mile-long (79.7 km) tributary of the Broad River in the U.S. state of Georgia. Via the Broad River it is part of the Savannah River watershed.The headwaters are in Banks County near the city of Homer. Grove Creek feeds into the Hudson near the Franklin County line. The river then constitutes most of the southern border of Franklin County separating it from Madison County.\n==>\n","completion":" NaturalPlace"} -{"prompt":" Bent Hansen (born 1954) is a retired Danish ice hockey forward. He played for 18 years in Denmark for the Rødovre SIK and KSF. He also competed for the Danish national team. His son Jannik Hansen also played for the Rødovre team and was drafted into the NHL by the Vancouver Canucks in 2004. During his hockey career Hansen also worked as a carpenter.\n==>\n","completion":" Athlete"} -{"prompt":" Merdani is a village in the municipality of Busovača Bosnia and Herzegovina.\n==>\n","completion":" Village"} -{"prompt":" Tulemalu Lake is a lake in Kivalliq Region Nunavut Canada.\n==>\n","completion":" NaturalPlace"} -{"prompt":" Popeyes Louisiana Kitchen is an American chain of fried chicken fast food restaurants founded in 1972 in New Orleans Louisiana. Often referred to as Popeyes and sometimes as Popeyes Chicken & Biscuits or Popeyes Chicken & Seafood[citation needed] it was acquired by Sandy Springs Georgia-based AFC Enterprises originally America's Favorite Chicken Company in 1993.\n==>\n","completion":" Company"} -{"prompt":" USS Spiegel Grove (LSD-32) was a Thomaston-class dock landing ship of the United States Navy. She was named for Spiegel Grove the home and estate in Fremont Ohio of Rutherford B. Hayes the 19th President of the United States.\n==>\n","completion":" MeanOfTransportation"} -{"prompt":" Martin G.S. Mansergh (born 31 December 1946) is a former Irish Fianna Fáil politician and historian. He was a Teachta Dála (TD) for the Tipperary South constituency from 2007 until 2011. He was previously a Senator from 2002 to 2007. He played a leading role in formulating Fianna Fáil policy on Northern Ireland.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Chris Nieratko (born February 19 1976) is an American humorist and author. Nieratko is a past editor of Big Brother Magazine and currently reviews pornographic films for Vice magazine as well as being the author of the related Skinema book. He also appeared on MTV's Jackass.\n==>\n","completion":" Artist"} -{"prompt":" Physena is the sole genus of the flowering plant family Physenaceae. It contains two species of shrubs and small trees which are endemic to Madagascar. The APG II system of 2003 (unchanged from the APG system of 1998) does recognize this family and assigns it to the order Caryophyllales in the clade core eudicots.\n==>\n","completion":" Plant"} -{"prompt":" Michael F. Kitt Snr (13 September 1914 – 24 December 1974) was an Irish Fianna Fáil politician and long-serving Teachta Dála (TD).He was elected to Dáil Éireann for the first time at the 1948 general election for the Galway North constituency but lost his seat at the 1951 general election and failed to be elected again at the 1954 general election.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Jelenin svet (Jelena's World) is a 2008 independent documentary film written and directed by Tanja Brzaković about former World No. 1 female tennis player Jelena Janković.\n==>\n","completion":" Film"} -{"prompt":" La combi asesina (The Killer Combination) is a 1982 Mexican film. It was directed by Gustavo Alatriste.\n==>\n","completion":" Film"} -{"prompt":" Šetonje is a village situated in Petrovac na Mlavi municipality in Serbia.\n==>\n","completion":" Village"} -{"prompt":" Mirbelia is a plant genus belonging to the Fabaceae family. It is endemic to Australia occurring in every mainland state except South Australia.\n==>\n","completion":" Plant"} -{"prompt":" Kaala Patthar (English: Black Stone) is a 1979 Indian Bollywood action\/drama film. It was produced and directed by Yash Chopra. The story was written by Salim-Javed. This film is the fourth collaboration between Amitabh Bachchan Shashi Kapoor and director Yash Chopra after the hugely successful Deewaar (1975) Kabhie Kabhie (1976) and Trishul (1978). However this film did average business at the box office. It was nominated for Filmfare awards.\n==>\n","completion":" Film"} -{"prompt":" Warlock is a 1959 film released by Twentieth Century Fox and shot in DeLuxe Color and CinemaScope. It is a Western adapted from the novel by Oakley Hall (screenplay written by Robert Alan Aurthur).\n==>\n","completion":" Film"} -{"prompt":" Jacob LeBlanc (born February 2 1981 in Auburn California) is an American retired professional soccer player.\n==>\n","completion":" Athlete"} -{"prompt":" The Pârâul Sărății is a tributary of the Cibin River in Romania.\n==>\n","completion":" NaturalPlace"} -{"prompt":" Draba incrassata is an uncommon species of flowering plant in the mustard family known by the common name Sweetwater Mountains draba. It is endemic to California where it is known mainly from the Sweetwater Mountains of Mono County. It grows in alpine rock fields on the barren high mountain peaks. Draba incrassata is a small perennial herb forming mats of thick oval-shaped leaves.\n==>\n","completion":" Plant"} -{"prompt":" William Thomas Burton (31 January 1878 in Black Rock St Michael Barbados – 22 August 1946 St Michael Barbados) was a coloured West Indian cricketer best known as a member of the 1900 and 1906 West Indian tourists to England. He is generally known as Tommie Burton.He was the son of a black mother and a white father. He was brought up in Barbados and served for some years there as a practice bowler and in trial matches.\n==>\n","completion":" Athlete"} -{"prompt":" Shukan ST is a weekly newspaper published by The Japan Times for learners of English language. It is originally titled as Student Times but changed to Shukan ST since a significant portion of its readers are not students. It has articles on news movie lifestyle in English-speaking countries opinions and other kinds attracting learners of English and helping them with notes on terms.\n==>\n","completion":" Company"} -{"prompt":" Salempur Masanda is a village in Jalandhar District near the Jalandhar Cantonment in Punjab India.\n==>\n","completion":" Village"} -{"prompt":" Shelton Hank Williams also known as Hank Williams III and Hank 3 (born December 12 1972) is an American musician singer and multi-instrumentalist including guitar bass drums banjo and vocals. In addition to his honky tonk recordings Williams' style alternates between country punk and metal.\n==>\n","completion":" Artist"} -{"prompt":" Grand Lake is a large lake in the interior of Newfoundland of the Canadian province of Newfoundland and Labrador. It has an area of 534 km² making it the largest lake on Newfoundland. Consequently it is one of if not the deepest.\n==>\n","completion":" NaturalPlace"} -{"prompt":" Thatching (31 May 1975 – 1999) was an Irish Thoroughbred racehorse and sire. The horse's early career was delayed and disrupted by injury and he did not show his best form until switched to sprinting distances in the spring of 1979 when he won the Duke of York Stakes. He improved further when equipped with blinkers that summer recording impressive victories in both the Cork and Orrery Stakes and the July Cup.\n==>\n","completion":" Animal"} -{"prompt":" John Edward Hatton AO (born 29 May 1933) is former Australian politician and an National Trust of Australia nominated Australian Living Treasure. He was the independent member of the Legislative Assembly of the New South Wales parliament for the seat of South Coast from 1973 to 1995. Notably the allegations about police corruption Hatton raised in Parliament resulted in the Wood Royal Commission. He is currently a social activist in his local community.\n==>\n","completion":" OfficeHolder"} -{"prompt":" The Tiger Hotel is a hotel in Columbia Missouri. Built as a hotel in 1928 the building later housed a retirement home and banquet center. In 2012 the building was fully restored and reopened as a boutique hotel. It was listed on the National Register of Historic Places in 1980.\n==>\n","completion":" Building"} -{"prompt":" This article details Car Nos. 10–13 of the Manx Electric Railway on the Isle of Man.This was the third batch of motorcars delivered to the railway in 1895 at the same time as the cars for the new Snaefell Mountain Railway were delivered. They were constructed to a very similar design to those provided for the mountain line.\n==>\n","completion":" MeanOfTransportation"} -{"prompt":" The Charles Granke House at 406 S. Seventh St. in Hamilton Montana is a historic house that was built in 1906. It includes Colonial Revival and Queen Anne architecture. It was listed on the National Register of Historic Places in 1988. The listing included two contributing buildings.It was built in approximately 1906 by the Anaconda Copper Mining Company as a worker cottage for workers at the sawmill that operated in Hamilton until 1915. Charles W.\n==>\n","completion":" Building"} -{"prompt":" Renealmia is a plant genus in the family Zingiberaceae. Species include: Renealmia alpinia Renealmia aurantifera Renealmia cernua Renealmia dolichocalyx Renealmia oligotricha Renealmia sessilifolia Renealmia thrysoidesE.g. Alpinia nutans was formerly placed herein too.\n==>\n","completion":" Plant"} -{"prompt":" The Masonic Temple in Great Falls Montana is a building from 1914. It was listed on the National Register of Historic Places in 2000.Address is 821 Central Avenue Great Falls Motana 59401 Phone number is 453-9080.Cascade No. 34 meets 2nd and 4th Tuesdays at 7:30pm Sept-June.Euclid No. 58 meets year-round 1st and 3rd Tuesdays at 7:30pm Sept-May 3rd Tuesdays at 7:30pm June-Aug. Delta No. 128 meets 2nd Wednesdays at 7:30pm Sept-June.\n==>\n","completion":" Building"} -{"prompt":" Aricoceras is an extinct genus of the Adrianitidae family. They are an extinct group of ammonoid which are shelled cephalopods related to squids belemnites octopuses and cuttlefish and more distantly to the nautiloids.\n==>\n","completion":" Animal"} -{"prompt":" Stanhopea martiana is a species of orchid endemic to southwestern Mexico.\n==>\n","completion":" Plant"} -{"prompt":" The Fiat Barchetta (Italian pronunciation: [ˈfiat barˈketta]) (Type 183) is a roadster produced by the Italian manufacturer Fiat from 1995 to 2005 (though production was paused between May 2002 and 2004). Barchetta in Italian means 'little boat'.\n==>\n","completion":" MeanOfTransportation"} -{"prompt":" Pimelea ferruginea is a small shrub native to southwest Western Australia. It was described by Labillardiere in 1805.\n==>\n","completion":" Plant"} -{"prompt":" Symmoca dodecatella is a moth of the Symmocidae family. It is found in Portugal and Spain.The wingspan is about 18–19 mm. The forewings are grey sprinkled with black mainly along the margin. The hindwings are grey.\n==>\n","completion":" Animal"} -{"prompt":" The Madrisa (or Madrisahorn) is a mountain in the Rätikon mountain range overlooking Klosters in the Swiss canton of Graubünden. Its summit (2826 metres) is located near the Austrian border.The Madrisa is constituted by several secondary summits notably the Gargeller Madrisa (2770 metres) overlooking Gargellen in Austria.Ski lifts up to 2600 metres are located on the Klosters side.\n==>\n","completion":" NaturalPlace"} -{"prompt":" Dansere is an album by Jan Garbarek. The album was recorded in November 1975 and features the Bobo Stenson Quartet.\n==>\n","completion":" Album"} -{"prompt":" Frederick William Seward (July 8 1830 – April 25 1915) was the Assistant Secretary of State during the American Civil War serving in Abraham Lincoln's administration as well as under Andrew Johnson during Reconstruction and for over two years under Rutherford B. Hayes.\n==>\n","completion":" OfficeHolder"} -{"prompt":" The Incorporated VIllage of Westhampton Beach is an incorporated village in the Town of Southampton Suffolk County New York United States. As of the 2010 census the village population was 1721.\n==>\n","completion":" Village"} -{"prompt":" Sieniawa [ɕeˈɲava] is a village in the administrative district of Gmina Raba Wyżna within Nowy Targ County Lesser Poland Voivodeship in southern Poland. It lies approximately 5 kilometres (3 mi) south-east of Raba Wyżna 10 km (6 mi) north-west of Nowy Targ and 59 km (37 mi) south of the regional capital Kraków.The village has a population of 1900.\n==>\n","completion":" Village"} -{"prompt":" Zeisters also known as Fat Guy Goes Nutzoid is a 1986 comedy film produced by Troma Entertainment. Troma was originally set to title the film Fat Boy Goes Nutzoid but at the request of the lawyers of the hip-hop group The Fat Boys it was changed to Fat Guy.\n==>\n","completion":" Film"} -{"prompt":" Brian Schroeder (a.k.a. Pushead) is an artist record label owner and writer within the hardcore punk and heavy metal field. He has created artwork for many bands artists and athletes including Metallica The Misfits Dr. Dre Travis Barker Craig Johnson and Kool Keith. He has designed many record covers T-shirts skateboards and a pair of Nike SB Dunks. His record label Pusmort Records has released albums by Negative Gain Poison Idea and Final Conflict.\n==>\n","completion":" Artist"} -{"prompt":" Abdollah Masud-e Sofla (Persian: عبداله مسعودسفلي‎ also Romanized as ‘Abdollāh Mas‘ūd-e Soflá; also known as Abdollah Mas’ood ‘Abdollāh Mas‘ūd and Abdullāh Masūd) is a village in Hesar-e Valiyeasr Rural District Avaj District Buin Zahra County Qazvin Province Iran. At the 2006 census its population was 72 in 15 families.\n==>\n","completion":" Village"} -{"prompt":" R.C. Bigelow Inc better known as the Bigelow Tea Company is an American tea company based in Fairfield Connecticut. The company was founded by Ruth C. Bigelow in the late 1940s based on a recipe she marketed as Constant Comment tea. Bigelow is still a 100% family-owned business that markets over 50 varieties of tea including black and green as well as herbal teas all of which are still blended in Fairfield. They also own America's only tea plantation in Charleston South Carolina.\n==>\n","completion":" Company"} -{"prompt":" Turn of Faith is a 2001 film directed by Charles Jarrott. It stars Ray Mancini and Mia Sara.\n==>\n","completion":" Film"} -{"prompt":" Rani Kasula Rangamma is a Telugu film starring Chiranjeevi.\n==>\n","completion":" Film"} -{"prompt":" The Brown-patched Kangaroo lizard (Otocryptis wiegmanni) also called Wiegmann's Agama or Sri Lankan Kangaroo Lizard is a small ground dwelling agamid lizard endemic to the wet zone forests and lower mountain forests (up to 1300 metres) of Sri Lanka. It is commonly seen in the leaf litter of shady rain forests. When perceiving danger it spurts away quickly on its large hind legs and might eventually climb up a sapling or tree.\n==>\n","completion":" Animal"} -{"prompt":" The 20\/20 Experience – The Complete Experience is a compilation album by American singer-songwriter Justin Timberlake. It was released on September 27 2013 by RCA Records.\n==>\n","completion":" Album"} -{"prompt":" Under Cover 2 is the 5th solo album of Joe Lynn Turner released in 1999. Just like Under Cover the album consists mainly of covers of Turner's favourite artists.\n==>\n","completion":" Album"} -{"prompt":" Mykola Kanevets (Ukrainian: Микола Канівець) is the Artistic Director and Ballet Master of the Cheremosh Ukrainian Dance Company in Edmonton Alberta Canada.A native of Kiev Ukraine Mykola attended the National University of Culture and Performing Arts in Kiev Ukraine where he graduated from the Faculty of Choreography with the distinction of Ballet Master and Choreographer.\n==>\n","completion":" Artist"} -{"prompt":" Jimmy Cross (17 November 1938 - 8 October 1978) was an American radio producer and singer who attained a minor Billboard Hot 100 hit with the novelty song I Want My Baby Back in 1965. He was born in Dothan Alabama[citation needed] and became the producer of the syndicated radio series Country Concert.I Want My Baby Back was originally issued on the Tollie label and reached #92 on the Billboard Hot 100 in February 1965.\n==>\n","completion":" Artist"} -{"prompt":" Ruff Ryders: Past Present Future is the fifth compilation album from American hip hop record label Ruff Ryders Entertainment released on November 21 2011.\n==>\n","completion":" Album"} -{"prompt":" Brachyglottis huntii commonly called rautini or Chatham Island Christmas tree is a species in the Asteraceae family and is found only on the Chatham Islands in New Zealand.\n==>\n","completion":" Plant"} -{"prompt":" Megachile perihirta commonly known as the Western leafcutting bee is a bee in the genus Megachile. The bee is native to western North America ranging from Nebraska to Texas and Mexico west to California and north to British Columbia and Alberta and often inhabits meadows and orchards. The bee is black with long whitish-yellow hair more so below the thorax and abdomen. The abdomen however is mostly bare although each segment has scattered whitish hair.\n==>\n","completion":" Animal"} -{"prompt":" The Last Supper is the fourth album released by American stand-up comedian Jim Gaffigan. It focuses largely on his love of food.\n==>\n","completion":" Album"} -{"prompt":" A Colossal Failure of Common Sense: The Inside Story of the Collapse of Lehman Brothers is a 2009 non-fiction book written by Lawrence G. McDonald and Patrick Robinson which chronicles the events surrounding the bankruptcy of Lehman Brothers in the context of the financial crisis of 2007–2010 and the subprime mortgage crisis.\n==>\n","completion":" WrittenWork"} -{"prompt":" The American Motor Car Company was a short-lived company in the automotive industry founded in 1906 lasting until 1913. It was based in Indianapolis Indiana United States. The American Motor Car Company pioneered the underslung design.\n==>\n","completion":" Company"} -{"prompt":" Michael Adam (born 9 December 1984) is a German politician. He has been District Administrator (Landrat) of Regen since 2011.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Nuno Daniel Costeira Valente (born 22 November 1991 in Adaúfe - Braga ) is a Portuguese footballer who plays for Vizela on loan from S.C. Braga as a midfielder.\n==>\n","completion":" Athlete"} -{"prompt":" Living Fossil is a classic science fiction story on the concepts of human extinction and future evolution by L. Sprague de Camp. It was first published in the magazine Astounding Science-Fiction for February 1939. It first appeared in book form in the anthology A Treasury of Science Fiction (Crown Publishers 1948); it later appeared in the anthologies Gates to Tomorrow (Atheneum 1973) and The SFWA Grand Masters Volume 1 (Tor Books 1999).\n==>\n","completion":" WrittenWork"} -{"prompt":" Paul Gobeil (born March 1 1942 in Saint-Rémi-de-Tingwick Quebec) is a former Canadian politician and businessman.From 1985 to 1989 Mr. Gobeil was a Liberal member of the National Assembly for the riding of Verdun and served as Minister assigned to Administration President of the Treasury Board and as Minister of International Affairs for the Government of Quebec.\n==>\n","completion":" OfficeHolder"} -{"prompt":" USNS Mount Baker (T-AE-34) is the seventh of eight Kilauea-class ammunition ships to serve with the Military Sealift Command. She is the second U.S. Navy ship to bear the name and is named for Mount Baker a 10781-foot volcano in the Cascade Range of Washington. Ammunition ships operated by Military Sealift Command provide logistic support to US Navy ships at sea.Mount Baker was built by Ingalls Shipbuilding Pascagoula Mississippi.\n==>\n","completion":" MeanOfTransportation"} -{"prompt":" Robert Murray Waddington (24 October 1927 – 15 March 2007) was Dean of Manchester in the last quarter of the 20th century.Born in Bognor Regis on 24 October 1927 he was educated at Dulwich College Selwyn College Cambridge and Ely Theological College. Ordained in 1954 he began his career at St John’s Bethnal Green. Afterwards he was Chaplain at Slade School in Warwick Queensland. He returned to England in 1959 to join the Oratory of the Good Shepherd an order of celibate priests.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Then and Now is a historical novel by W. Somerset Maugham. Set in Florence Italy during the Renaissance the story focuses on three months in the life of Niccolo Machiavelli the Florentine politician diplomat philosopher and writer in the early years of the 16th century. The book was first published by Heinemann in 1946.\n==>\n","completion":" WrittenWork"} -{"prompt":" Malleable Iron Range Company was a company that existed from 1896 to 1985 and primarily produced kitchen ranges made of malleable iron but also produced a variety of other related products. The company's primary trademark was 'Monarch' and was colloquially often referred to as the Monarch Company or just Monarch.\n==>\n","completion":" Company"} -{"prompt":" MAKO Surgical Corp. (Stryker Medical) is a publicly traded medical device company based in Florida. On September 25 2013 the Board of Directors of Mako Surgical accepted a deal to merge with Stryker Medical for $1.65B subject to shareholder approval.\n==>\n","completion":" Company"} -{"prompt":" Mt. Kinka (金華山 Kinka-zan) also known as Kinkazan is located in the heart of the city of Gifu Gifu Prefecture Japan and rises to a height of 329 m (1079 ft). Previously called Mt. Inaba (稲葉山 Inaba-yama) it has long served as the representative symbol of Gifu. It stands along the Nagara River creating bountiful nature within the city. Though it is the most famous mountain in the city Mount Dodo to the north is the tallest.\n==>\n","completion":" NaturalPlace"} -{"prompt":" Emi Motoi (本井 えみ Motoi Emi born October 11 in Kanagawa) is a Japanese voice actress.\n==>\n","completion":" Artist"} -{"prompt":" Central National-Gottesman Inc. is one of the world's largest distributors of pulp paper paperboard and newsprint. The firm's products are sold in over 75 countries through a network of 43 offices located in the United States and abroad. With annual revenues exceeding $3 billion Forbes ranked Central National-Gottesman 137th in its annual list of The Largest Private Companies.\n==>\n","completion":" Company"} -{"prompt":" Behind the Sun is a 2004 album by Dive.\n==>\n","completion":" Album"} -{"prompt":" The Maple School District is a public school district in Douglas County Wisconsin United States based in Maple Wisconsin.\n==>\n","completion":" EducationalInstitution"} -{"prompt":" Nigma puella is a species of spider belonging to the family Dictynidae. It is found in Europe Azores Madeira Canary Islands and parts of North Africa.Like most members of the family this is a small spider but the female is striking with a light green abdomen marked with a bold maroon blotch and a variable amount of barring in the same colour. The male is reddish-brown. This species makes a horizontal web over the top surface of a leaf.\n==>\n","completion":" Animal"} -{"prompt":" St. Thomas Episcopal Church is a parish church in the Episcopal Diocese of Iowa. The church is located in Sioux City Iowa United States at 1200 Douglas Street. The church building is listed on the National Register of Historic Places.\n==>\n","completion":" Building"} -{"prompt":" Timothy Floyd Tim Burchett (born August 25 1964) is an American Republican politician currently the mayor of Knox County Tennessee. He previously served in Tennessee General Assembly first in the Tennessee House of Representatives and later in the Tennessee State Senate in which he represented Tennessee's District 7 part of Knox County. On August 5 2010 Burchett was elected mayor of Knox County replacing Mike Ragsdale.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Sukeban Deka The Movie (スケバン刑事) is a live action Japanese film that was released in 1987. The movie closely follows a TV and manga series Sukeban Deka written and illustrated by Shinji Wada. The movie stars Yoko Minamino and Yui Asaka who were also in the TV series. The movie was followed by Sukeban Deka II in 1988.\n==>\n","completion":" Film"} -{"prompt":" Dr. Joseph de Graft-Johnson (1933–1999) was an engineer academic and politician. He became the Vice-President of Ghana between 1979 and 1981.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Oxmoor Center is a Louisville Kentucky shopping mall located at 7900 Shelbyville Road in eastern Louisville.\n==>\n","completion":" Building"} -{"prompt":" Springhill High School (SHS) is a secondary school in Springhill Nova Scotia Canada. SHS is part of the Chignecto-Central Regional School Board and is the only high school in the town of Springhill. The school is home to many sports teams and clubs. These include: basketball soccer badminton track and field softball Students Against Destructive Decisions drama club homework club and book club.\n==>\n","completion":" EducationalInstitution"} -{"prompt":" The Chiltern School is a coeducational special school located over two sites in Dunstable and Houghton Regis in Bedfordshire England. The school accepts pupils from all over the Central Bedfordshire area.The school was formed in 2012 from the merger of Glenwood School in Dunstable and Hillcrest School in Houghton Regis.\n==>\n","completion":" EducationalInstitution"} -{"prompt":" Death from Above is a 2011 horror film by director Bruce Koehler. The film features professional wrestling stars Kurt Angle Sid Eudy James Storm Matt Morgan Terry Gerin and Jessica Kresa.\n==>\n","completion":" Film"} -{"prompt":" Le Cadeau released in Italy as Il regalo is a 1982 French and Italian film. It stars Claudia Cardinale.\n==>\n","completion":" Film"} -{"prompt":" Deltocolpodes is a genus of beetles in the family Carabidae containing the following species: Deltocolpodes brendelli Morvan 1992 Deltocolpodes championi Morvan 1992 Deltocolpodes duluchus Morvan 1992 Deltocolpodes heinigeri Morvan 1992 Deltocolpodes jalepensis Morvan 1992 Deltocolpodes kirschenhoferi Morvan 1992 Deltocolpodes nepalensis Morvan 1992 Deltocolpodes perreaui Deuve 1985 Deltocolpodes rectangulus Morvan 1992 Deltocolpodes rolex Morvan 1992 Deltocolpodes salpensis Deuve 1985 Deltocolpodes sikkimensis Morvan 1992↑\n==>\n","completion":" Animal"} -{"prompt":" Ennea is a genus of air-breathing land snails terrestrial pulmonate gastropod mollusks in the family Streptaxidae.Ennea is the type genus of the subfamily Enneinae.\n==>\n","completion":" Animal"} -{"prompt":" Andersons Creek is a creek in Warrandyte and Park Orchards east of Melbourne Victoria Australia. It is a tributary of the Yarra River.\n==>\n","completion":" NaturalPlace"} -{"prompt":" Jason Gary King (born 13 April 1985 in Maidstone England) is a speedway rider who was formerly the club captain of Newcastle Diamonds in the British Premier League. His brother Daniel is also a speedway rider.\n==>\n","completion":" Athlete"} -{"prompt":" Ridi Viharaya (Sinhala: රිදී විහාරය) or Silver Temple is a 2nd-century BCE Theravada Buddhist temple in the village of Ridigama Sri Lanka. Built during the reign of Dutthagamani of Anuradhapura the temple is considered as the place where the silver ore which provided silver to complete Ruwanwelisaya; one of the largest stupa in Sri Lanka was discovered.\n==>\n","completion":" Building"} -{"prompt":" Wang Yuanping (born 8 December 1976) is a retired Chinese athlete who specialised in the 800 metres. She won several medals at the regional level.Her personal bests in the event are 2:00.63 seconds outdoors (Jinzhou 2000) and 2:03.41 seconds indoors (Yokohama 2004).\n==>\n","completion":" Athlete"} -{"prompt":" The Atakora River is a tributary of Lake Volta in Ghana it flows about 60 km east to the Lake Volta. Its entire course is in south Ghana.\n==>\n","completion":" NaturalPlace"} -{"prompt":" Charniele L. Herring (\/ʃɑrˈnɛl ˈhɛrɪŋ\/ shar-NEL HERR-ing; born September 25 1969) is an American politician. She has served in the Virginia House of Delegates since 2009 representing the 46th district made up the city of Alexandria and part of Fairfax County near Washington D.C. Herring is a member of the Democratic Party. She has been the House minority whip since 2012 and in December 2012 she was the first African-American to be elected chair of the Democratic Party of Virginia.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Worlds Beyond was an American digest magazine of science fiction and fantasy fiction in 1950 and 1951. The magazine only issued three monthly issues from December 1950 to February 1951 but is notable for having printed stories by Cyril M. Kornbluth Jack Vance Mack Reynolds Graham Greene John Christopher Lester del Rey Judith Merril and others.Worlds Beyond was published by Hillman Periodicals and was edited by Damon Knight.\n==>\n","completion":" Company"} -{"prompt":" Joseph Hubert Ruetz (October 21 1916 – January 2 2003) was a professional football player in the All-America Football Conference for the Chicago Rockets in 1946 and 1948. Prior to that he played at the collegiate level while attending the University of Notre Dame. He played guard for the Irish with the exception of playing one season at quarterback. In 1938 he graduated from Notre Dame with cum laude honors.\n==>\n","completion":" Athlete"} -{"prompt":" Ali Abbasov Mammad oglu (Azerbaijani: Əli Abbasov Məmməd oğlu) (born 1953 in Azerbaijan) is the current Minister of Communications and Information Technologies of the Republic of Azerbaijan.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Jean-François Imbernon (born October 17 1951 in Perpignan France is a retired French international rugby union player.He played as a Lock for USA Perpignan. He earned his first cap with the French national team on 7 February 1976 against Ireland at Parc des Princes.\n==>\n","completion":" Athlete"} -{"prompt":" Patties Foods (previously Patties Bakery) is an Australian food manufacturing company that produces meat pies baked goods frozen fruits and pre-made desserts. Headquartered in Bairnsdale Victoria Australia Patties Foods is represented in the Australian market by the Four'N Twenty Patties Herbert Adams Creative Gourmet Nanna's and Chefs Pride brands. Patties is the largest meat pie producing company in Australia and the world.\n==>\n","completion":" Company"} -{"prompt":" Pop Carn is a 2003 Indian Tamil film written and directed by actor-cum-director Nassar and starring Mohanlal and Simran Bagga in lead roles and introducing newcomers Kunal Shah and Jyothi Nawal. The film which had music scored by Yuvan Shankar Raja was released on 30 January 2003 but flopped at the box office. Nonetheless the film was dubbed into Malayalam and released in 2007 under the same name.\n==>\n","completion":" Film"} -{"prompt":" The Daily News Journal commonly abbreviated to DNJ is a newspaper serving Murfreesboro Tennessee Rutherford County and surrounding communities. Published in Murfreesboro it serves as the primary local newspaper with competition from The Murfreesboro Post and other publications. The newspaper is not in competition with The Tennessean of Nashville as both are owned by Gannett Company.The roots the DNJ date back to 1849 and the founding of Murfreesboro News.\n==>\n","completion":" WrittenWork"} -{"prompt":" Sinéad Madden (born in Galway Ireland) is an Irish singer-songwriter and fiddle player best known as a member of the Moya Brennan band. She also teaches at Waltons New School of Music in Dublin.\n==>\n","completion":" Artist"} -{"prompt":" Morada Limited is a textile company based in Altham Lancashire. Morada specializes in curtains.\n==>\n","completion":" Company"} -{"prompt":" Passiflora monadelpha is a species of plant in the Passifloraceae family. It is endemic to Ecuador.\n==>\n","completion":" Plant"} -{"prompt":" The White Umfolozi River originates just south of Vryheid KwaZulu-Natal South Africa and joins the Black Umfolozi River at 28°20′58″S 31°58′46″E to form the Umfolozi River before it flows east towards the Indian Ocean.\n==>\n","completion":" NaturalPlace"} -{"prompt":" USS Tuluran (AG-46) – also known as USS Lake Superior (ID-2995) – was a commercial cargo ship acquired by the U.S. Navy for service during both World War I when she was known as USS Lake Superior and also during World War II when she was known as USS Tuluran.\n==>\n","completion":" MeanOfTransportation"} -{"prompt":" Blackburn High School is a public secondary school for girls and boys in years 7 to 12 in Blackburn a suburb of Melbourne Victoria Australia. Blackburn High School is an outstanding secondary school for aspiring young men and women. It aims to educate tomorrow's minds today. Started in 1956 the school has a proud tradition of academic excellence and exceptional music achievement.The school is nationally recognised as a leading educational institution for music education.\n==>\n","completion":" EducationalInstitution"} -{"prompt":" Mount Carmel – Blytheswood Public School is an elementary school in the north end of Leamington Ontario Canada. It is part of the Greater Essex County District School Board and serves students from JK to Grade 8 from the communities of Blytheswood and Mount Carmel and surrounding areas.\n==>\n","completion":" EducationalInstitution"} -{"prompt":" The IAR 79 is a bi-engine bomber military reconnaissance aircraft with a wood and metal structure that saw service in World War II built under licence in Brasov Romania by Industria Aeronautică Română\n==>\n","completion":" MeanOfTransportation"} -{"prompt":" Jaagoo (Bengali: জাগো) is a Bangladeshi sports based romantic Movies. Its writer and director Khijir Hayat Khan. Adnan Karim sponsored youth football game built this film was released in 2010. The film is produced by Sharjeel Karim and Adnan Karim and directed by Khijir Hayat Khan who has written the story screenplay and dialogues of the film. The film features Ferdous Ahmed and Afsana Ara Bindu in lead roles and with supporting Arefin Shuvo Tariq Anam Ronok Hasaan and many more.\n==>\n","completion":" Film"} -{"prompt":" The African Queen is a 1951 adventure film adapted from the 1935 novel of the same name by C. S. Forester. The film was directed by John Huston and produced by Sam Spiegel and John Woolf. The screenplay was adapted by James Agee John Huston John Collier and Peter Viertel. It was photographed in Technicolor by Jack Cardiff and had a music score by Allan Gray.\n==>\n","completion":" Film"} -{"prompt":" Arenaria ursina is a species of flowering plant in the pink family known by the common name Bear Valley sandwort.\n==>\n","completion":" Plant"} -{"prompt":" Charles Corm (1894-1963) was a Lebanese writer businessman and philanthropist. He is considered to be the leader of the Phoenicianism movement in Lebanon which ignited a surge of nationalism that led to Lebanon's independence. In a country torn by sectarian conflicts Corm's intention was to find a common root shared by all Lebanese beyond their religious beliefs (the Phoenicians were pagans).\n==>\n","completion":" Artist"} -{"prompt":" The University of Nevada School of Medicine is an academic division of the University of Nevada Reno and grants the Doctor of Medicine (MD) degree. The School of Medicine was founded in 1969 as the first medical school in the state of Nevada. More than 1500 MDs have graduated from the School of Medicine. The pre-clinical campus is located in Reno but the third and fourth years can be spent in hospitals and clinics throughout Nevada.\n==>\n","completion":" EducationalInstitution"} -{"prompt":" Leon Kroll (December 6 1884 – October 25 1974) was an American painter and lithographer. Known as a figurative artist Life Magazine described him as the dean of U.S. nude painters yet he was an exceptional landscape painter and also produced an exceptional body of still life compositions.Born into a musical family on lower Second Avenue in New York City Kroll's father was a violinist and his cousin was William Kroll.\n==>\n","completion":" Artist"} -{"prompt":" Harold Frederick Weaver Hawkins (1893-1977) was an English painter who specialized in ambitious sometimes mural-sized modernist allegories of morality for an age of atomic warfare and global over-population.\n==>\n","completion":" Artist"} -{"prompt":" Ghostquake (also known as Haunted High) is a 2012 American made-for-television horror film produced by Syfy. The film was directed by Jeffrey Lando and written by Paul A. Birkett and Anthony C. Ferrante. The film stars Danny Trejo and MC Gainey. It follows a group of high school students trying to escape the wrath of a few ghastly spirits following an earthquake at their school Holloman High School.\n==>\n","completion":" Film"} -{"prompt":" The Valley is the first novel by Barry Pilton published in 2005 by Bloomsbury. It is a humorous account of the effect of outsiders on the rural status quo in a fictional mid-Wales valley during the 1980s and is being adapted for television.\n==>\n","completion":" WrittenWork"} -{"prompt":" Echinocereus fendleri is a species of cactus known by the common names pinkflower hedgehog cactus and Fendler's hedgehog cactus. It grows in deserts and woodlands in the Southwestern United States and Northeastern Mexico. It is most common in New Mexico.The taxonomy of the species is uncertain with authors recognizing up to eight varieties.\n==>\n","completion":" Plant"} -{"prompt":" Thapanzeik is a village in Homalin Township Hkamti District in the Sagaing Region of northwestern Burma.\n==>\n","completion":" Village"} -{"prompt":" Jeff Chapman (born July 17 1969 in Brunswick Georgia) is the bass singer for the Kingdom Heirs. He has been a member of the group since 2002. He has previously traveled with Bob Wills The Sound The Anchormen and The Blackwoods.He has twice been nominated as favorite bass in the Singing News fan awards.Chapman has a wife Angie two sons Justin and Sean and daughter Taylor.\n==>\n","completion":" Artist"} -{"prompt":" River Roads Mall was an enclosed shopping mall located in the city of Jennings a suburb of St. Louis Missouri United States. Opened in 1962 as one of the nation's first shopping malls the mall declined in the 1990s becoming a dead mall and eventually being shuttered in 1995. Demolition of the long-vacant mall began in 2006.\n==>\n","completion":" Building"} -{"prompt":" The Kout Food Group is a Kuwaiti-based conglomerate founded in 1982.In Kuwait it operates franchises of Burger King Pizza Hut and Taco Bell.Its UK arm Kout Food Group Restaurants UK it operates under brands such as Burger King KFC and Maison Blanc. In August 2013 it acquired the Little Chef chain for £15 million.\n==>\n","completion":" Company"} -{"prompt":" Jay Cashman Inc. is an American heavy-construction company based in Quincy Massachusetts with satellite offices in Boston Jupiter Florida and Staten Island New York. As of 2006 the company has about 1000 employees. The company was one of the major contractors on the Boston's Central Artery\/Tunnel Project. In 2004 Jay Cashman Inc.\n==>\n","completion":" Company"} -{"prompt":" The Albatros L 74 was a two-seated German training biplane produced by Albatros Flugzeugwerke. Only two were produced.\n==>\n","completion":" MeanOfTransportation"} -{"prompt":" Luktvatnet is a lake that lies in the northern part of the municipality of Vefsn in Nordland county Norway. The lake lies between the mountains Korgfjellet and Lukttinden about 5 kilometres (3.1 mi) south of Elsfjord. The European route E06 highway passes along the northern shore of the lake.\n==>\n","completion":" NaturalPlace"} -{"prompt":" Yaşar Kurt (Armenian: Յաշար Կուրթ b.August 16 1968 in Istanbul Turkey) is a Turkish-Armenian rock artist.\n==>\n","completion":" Artist"} -{"prompt":" Planning the Play of a Bridge Hand is a book on contract bridge co-written by Canadian teacher and author Barbara Seagram and British author David Bird. It was published by Master Point Press in 2009.The book teaches novice bridge players some basic techniques of declarer play including suit establishment ruffing losers and the finesse.\n==>\n","completion":" WrittenWork"} -{"prompt":" Helicella orzai is a species of air-breathing land snails terrestrial pulmonate gastropod mollusks in the family Hygromiidae the hairy snails and their allies. This species is endemic to Spain.\n==>\n","completion":" Animal"} -{"prompt":" Margaret Anderson Kelliher (born March 11 1968) is a Minnesota politician and a former member of the Minnesota House of Representatives. A member of the Minnesota Democratic–Farmer–Labor Party she represented District 60A which includes portions of the city of Minneapolis in Hennepin County located in the Twin Cities metropolitan area. First elected in 1999 she served until 2011 also serving as the Speaker from 2007 to 2011.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Kevin B. Kamenetz is the 12th and current County Executive of Baltimore County Maryland serving since 2010. He is a member of the Democratic Party. He previously served as a four-term County Councilman representing the Second District of Baltimore County.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Toni Amboaje is a Spanish singer who currently works for metal band Sauze which formed on early 2008.\n==>\n","completion":" Artist"} -{"prompt":" Kamam (Persian: كامم‎ also Romanized as Kāmam) is a village in Mangur-e Sharqi Rural District Khalifan District Mahabad County West Azerbaijan Province Iran. At the 2006 census its population was 98 in 16 families.\n==>\n","completion":" Village"} -{"prompt":" Sema Group plc was an Anglo-French IT services company. It was listed on the London Stock Exchange and was a constituent of the FTSE 100 Index but was acquired by Schlumberger in 2001.\n==>\n","completion":" Company"} -{"prompt":" Qadi Mahalleh (Persian: قادي محله‎ also Romanized as Qādī Maḩalleh) is a village in Pazevar Rural District Rudbast District Babolsar County Mazandaran Province Iran. At the 2006 census its population was 228 in 59 families.\n==>\n","completion":" Village"} -{"prompt":" Catharanthus roseus commonly known as the Madagascar rosy periwinkle is a species of Catharanthus native and endemic to Madagascar. Other English names occasionally used include Cape periwinkle rose periwinkle rosy periwinkle and old-maid.\n==>\n","completion":" Plant"} -{"prompt":" Portraits of Cuba is an album by Cuban musician Paquito D'Rivera released through Chesky Records in 1996. In 1997 the album won D'Rivera the Grammy Award for Best Latin Jazz Performance.\n==>\n","completion":" Album"} -{"prompt":" The Three Horseshoes is a public house in Drybridge Street in the Overmonnow area of Monmouth Wales. The pub has also been used as an Inn and also known as The Three Horse Shoes Inn. The building has been a Grade II Listed building since 15 August 1974. 19th century 2 storeys roughcast as stone with a hooded doorway\n==>\n","completion":" Building"} -{"prompt":" The Reef House is a historic house located at 411 S. Poplar St. in Carbondale Illinois. William A. Reef built the house for his family circa 1892. The Queen Anne-style cottage may have been designed by local carpenter A. M. Etherton though records of its designer do not exist. The house features fishscale shingle siding on its second floor and clapboard siding on its first; the clapboard siding is adorned with stickwork.\n==>\n","completion":" Building"} -{"prompt":" The Miami Center is a skyscraper in downtown Miami Florida. Although Miami Center is not the city's tallest building it is a symbol of early downtown. Built in 1983 it is older compared with most of the taller buildings in Miami which have been built in the last decade. In addition the Miami Center is immediately adjacent to Bayfront Park and is unobstructed when looking at the skyline from Miami Beach to the east. The building is 484 ft (148 m) tall and has 34 floors.\n==>\n","completion":" Building"} -{"prompt":" Acmella is a genus of thirty species of plants in the aster family Asteraceae. It is native to the Americas and has been introduced to Asia Africa the Pacific islands and Australia.One familiar species is Acmella oleracea which has been widely cultivated for centuries. It is used for food and medicine and as an insecticide and an ornamental plant.\n==>\n","completion":" Plant"} -{"prompt":" Andie Tong is a comic book artist known for his work on books such as Spectacular Spider-Man UK The Batman Strikes! and Tangent: Superman's Reign.\n==>\n","completion":" Artist"} -{"prompt":" Mount Whittier is a mountain in Carroll County New Hampshire in the northern Ossipee Mountains. Named after John Greenleaf Whittier the peak is not to be confused with nearby Nickerson Mountain which was once known as Mount Whittier.There are no hiking trails on Mount Whittier. There was once a CCC alpine ski trail on the northern face.\n==>\n","completion":" NaturalPlace"} -{"prompt":" Book Of Matches is a poetry book written by Simon Armitage first published in 1993 by Faber and Faber. Several poems featured in the book are studied as part of the GCSE English Literature examination in the UK.The book is written in three sections the first (Book of Matches) containing 30 short sonnets. Each is meant to be read within 20 seconds the amount of time it would take for a match to be lit and burn out.\n==>\n","completion":" WrittenWork"} -{"prompt":" The Brewer's Art is a Baltimore Maryland brewpub and restaurant. Opened on Friday September 13 1996. In 2008 it was named by Esquire magazine as the #1 Best Bar in America.\n==>\n","completion":" Company"} -{"prompt":" Jenna Rose Swerdlow (born September 28 1998) is an American teenage singer who gained media attention as a pre-teen with her single My Jeans. After the video went viral on YouTube and received 14 million views Swerdlow is considered a semi-viral star.\n==>\n","completion":" Artist"} -{"prompt":" Karl Nabersberg (sometimes written as Carl Nabersberg) was a German youth leader.Nabersberg was the son of a Crefeld shopkeeper. In 1923 he joined the Jugendorganisation the forerunner of the Hitler Youth in his home town. On 28 December 1925 he was admitted as a member of the National Socialist German Workers' Party (member number 26269) and as a member of the Sturmabteilung.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Down in the Shacks Where the Satellite Dishes Grow is the second album by the Judybats released in 1992.\n==>\n","completion":" Album"} -{"prompt":" Joe Cuba a.k.a Sonny (April 22 1931 – February 15 2009) was a musician of Puerto Rican descent who was known as the Father of Latin Boogaloo.\n==>\n","completion":" Artist"} -{"prompt":" David John Weatherley (born 1 March 1939) is a New Zealander actor known for his roles as Spencer the butler and the voice of Benglo the Fearcat in Power Rangers Operation Overdrive and Barliman Butterbur in The Lord of the Rings: The Fellowship of the Ring.Weatherley was born in London England and moved to Canada for a military career. He eventually moved to New Zealand to engage in a theatre acting career.\n==>\n","completion":" Artist"} -{"prompt":" William Lindsay (September 4 1835 – October 15 1909) was a Democratic U.S. Senator from Kentucky from 1893 to 1901.Born near Lexington Virginia Lindsay attended the common schools and settled in Clinton Kentucky in 1854. There he taught school and studied law. He was admitted to the bar and commenced practice in Clinton in 1858.\n==>\n","completion":" OfficeHolder"} diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/dbpedia_samples_prepared_valid.jsonl b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/dbpedia_samples_prepared_valid.jsonl deleted file mode 100644 index e18570283ba66d4cca359d02a83e5919463b250b..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/dbpedia_samples_prepared_valid.jsonl +++ /dev/null @@ -1,40 +0,0 @@ -{"prompt":" The Armenian Mirror-Spectator is a newspaper published by the Baikar Association in Watertown Massachusetts.\n==>\n","completion":" WrittenWork"} -{"prompt":" The Spice of Life is a smooth jazz studio album by Earl Klugh released in April 2008. The album received a Grammy nomination for Best Pop Instrumental Album at the 51st Grammy Awards in 2009.\n==>\n","completion":" Album"} -{"prompt":" Lindsay Ell is a country music singer songwriter and guitarist from Calgary Alberta.She performed at the South by Southwest music festival held in Austin Texas in March 2009 the welcome reception of the 2009 Juno Awards held in Vancouver British Columbia and was also a featured artist at the 2010 Winter Olympics.\n==>\n","completion":" Artist"} -{"prompt":" Scopula fuscata is a moth of the Geometridae family. It is found from south-western Saskatchewan west to British Columbia and south to California and Arizona. The habitat consists of montane areas including foothills.The wingspan is 24-28 mm. The wings and body are light tan sprinkled with darker yellow-brown or grey-brown scales. There is one generation per year with adults on wing in late June and early July in the northern part of the range.\n==>\n","completion":" Animal"} -{"prompt":" Daniel Lawrence Dan Whitney (born February 17 1963) best known by his stage name and character Larry the Cable Guy is an American stand-up comedian actor voice actor and former radio personality.\n==>\n","completion":" Artist"} -{"prompt":" Fab Five: The Texas Cheerleader Scandal is a Lifetime Television made-for-TV drama film starring Jenna Dewan Ashley Benson and Tatum O'Neal and directed by Tom McLoughlin. The film premiered on August 2 2008. It is based on a true story which occurred at McKinney North High School in McKinney Texas in 2006 in which five teenage cheerleaders became notorious for bullying truancies violations of the school dress code and general disrespect to the school community and authority.\n==>\n","completion":" Film"} -{"prompt":" Eungella Dam is one of Queensland's more established freshwater fisheries. Eungella has made a name for producing extra oversized Sooty grunter and more recently Barramundi.Eungella Dam was constructed in 1969 to meet the requirements of a thermal power station at Collinsville and the town water requirement of Collinsville and Scottsville.\n==>\n","completion":" NaturalPlace"} -{"prompt":" Hawkeye & Mockingbird was a comic book ongoing series published by Marvel Comics starring superheroes Hawkeye and Mockingbird.\n==>\n","completion":" WrittenWork"} -{"prompt":" John Whitlow Wyatt (September 27 1907 – July 16 1999) was a professional baseball pitcher. He played all or part of sixteen seasons in Major League Baseball for the Detroit Tigers (1929–33) Chicago White Sox (1933–36) Cleveland Indians (1937) Brooklyn Dodgers (1939–44) and Philadelphia Phillies (1945). While injuries sidetracked much of Wyatt's early career he is most famous for his performance in 1941 when his team (the Dodgers) won the National League pennant.\n==>\n","completion":" Athlete"} -{"prompt":" Sten Stjernqvist is a Swedish former footballer who played as a forward.\n==>\n","completion":" Athlete"} -{"prompt":" David Parlett (born 1939) is a games scholar from South London who has studied both card games and board games. His published works include many popular books on games and the more academic volumes The Oxford Guide to Card Games and The Oxford History of Board Games both now out of print. Parlett also invented a number of board games the most successful of which is Hare and Tortoise (1974). The German edition was awarded Spiel des Jahres (Game of the Year) in 1979.\n==>\n","completion":" Artist"} -{"prompt":" Double Butte is the 2579-foot (786 m) mountain summit distinguished by two buttes (the other at abou 2480 feet or 756 metres) in Riverside County California. It is the western most summit of a mountain range north of Winchester California east of Perris Valley and west of the San Jacinto Valley. The eastern ridge is composed primarily of metamorphic rock of the Triassic - Jurassic French Valley formation.\n==>\n","completion":" NaturalPlace"} -{"prompt":" The American Journal of Gastroenterology is a peer-reviewed medical journal published for the American College of Gastroenterology by the Nature Publishing Group.\n==>\n","completion":" WrittenWork"} -{"prompt":" Panicum anceps is a species of grass known by the common name beaked panicgrass. It is native to the southeastern United States where it occurs as far north as New Jersey and as far west as Kansas and Texas.This species is a rhizomatous perennial grass with stems growing up to 1.3 meters tall. The leaves have erect blades up to half a meter tall. The inflorescence is a panicle up to 40 centimeters long bearing pale green or yellowish spikelets. The grass produces an abundance of seed.\n==>\n","completion":" Plant"} -{"prompt":" Temporary Temple is a live album by Psychic TV. The album was recorded on July 28 1984 in London and released on 12 vinyl. It was later coupled with another concert and released on CD as Temporary Temple & Atonal.\n==>\n","completion":" Album"} -{"prompt":" La hija de Juan Simón (Juan Simón's Daughter) is a musical play by Nemesio M. Sobrevila which has been made into two Spanish films. It is also the name of the title track and the song has been recorded by numerous artists such as Leonardo Favio.The first film directed by José Luis Sáenz de Heredia was released in 1935 and starred Angelillo Pilar Muñoz and Manuel Arbó. Luis Buñuel was the executive producer for Filmófono and had a small role as an actor.\n==>\n","completion":" Film"} -{"prompt":" Duboisia hopwoodii is a shrub native to the arid interior region of Australia. Common names include pituri pitchuri thornapple or pitcheri. It has an erect habit usually growing to between 1 and 3 metres in height and has long narrow leaves. Flowers are white and bell-shaped with violet-striped throats. These appear between June and November in the species native range followed by purple-black rounded berries which are 3 to 6 mm in diameter.\n==>\n","completion":" Plant"} -{"prompt":" Thomas Eyre(fl. 1890s) was a footballer who made 65 appearances in the Football League playing for Lincoln City. He played at left back. Either side of Lincoln he played for Ashfield and Hamilton Academical in Scotland.\n==>\n","completion":" Athlete"} -{"prompt":" Kim Dae-Eun (born September 17 1984) is a South Korean gymnast. He is the 2004 Olympic All-around silver medalist. He won the gold medal on the parallel bars at the 2007 World Artistic Gymnastics Championships.Kim was part of the South Korean team that won the bronze medal in the team event at the 2006 Asian Games.\n==>\n","completion":" Athlete"} -{"prompt":" Arayik Vladimirovich Harutyunyan (Armenian: Արայիկ Հարությունյան Russian: Араик Арутюнян) (born 14 December 1973) is the current Prime Minister of the Nagorno-Karabakh Republic. He was suggested by the President of Nagorno-Karabakh Bako Sahakyan and was unanimously approved by the Parliament of Karabakh on 14 September 2007 by 32 out of 32 present parliamentarians.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Große Schmalenau is a river of North Rhine-Westphalia Germany.\n==>\n","completion":" NaturalPlace"} -{"prompt":" The Tupolev ANT-29 (military designation DIP – Dvukhmotorny istrebitel pushechny twin-engined cannon fighter) was a 1930s twin-engined cannon-armed fighter designed by Alexander Arkhangelsky and built by Tupolev.Design work started in 1932 on a twin-engined aircraft capable of carrying two APK-100 cannons. The resulting design was the ANT-29 and it first flew in February 1935. A monoplane with a tall and narrow fuselage and powered by two Hispano-Suiza 12Ybrs engines.\n==>\n","completion":" MeanOfTransportation"} -{"prompt":" The Dăihățașu River is a tributary of the Dumbrăvanu River in Romania.\n==>\n","completion":" NaturalPlace"} -{"prompt":" Grand Canyon Preparatory Academy is a public charter college preparatory school in Tempe Arizona.\n==>\n","completion":" EducationalInstitution"} -{"prompt":" Nayef Al Khater (born May 10 1978) is a Qatari football player. He currently plays for Al Wakrah as a defender.\n==>\n","completion":" Athlete"} -{"prompt":" Black Cobra Woman (Italian: Eva nera) also known as Black Cobra is an Italian 1976 exploitation movie written and directed by Joe D'Amato.\n==>\n","completion":" Film"} -{"prompt":" Thomas Frederick Fred Peart Baron Peart PC (30 April 1914 – 26 August 1988) was a British Labour politician who served in the Labour governments of the 1960s and 1970s and was a candidate for Deputy Leader of the Party.\n==>\n","completion":" OfficeHolder"} -{"prompt":" Epidendrum mancum is an epiphytic orchid that grows in the tropical low elfin cloud forests of Ecuador and Amazonas Peru at altitudes of 2—3 km .\n==>\n","completion":" Plant"} -{"prompt":" Yaleh Gonbad (Persian: يله گنبد‎; also known as Emāmzādeh Imamzade-Ele-Geumbez and Imāmzādeh) is a village in Ilat-e Qaqazan-e Gharbi Rural District Kuhin District Qazvin County Qazvin Province Iran. At the 2006 census its population was 429 in 105 families.\n==>\n","completion":" Village"} -{"prompt":" Michael E. DeBakey High School for Health Professions at Qatar (DHSHP@Q in short) is a private international middle and secondary school in Doha Qatar. The school is a branch campus of Michael E. DeBakey High School for Health Professions of Houston Texas United States. Charlesetta Deason is the CEO and President.Named after Michael E. DeBakey the school opened in September 2008 with grades 8 through 10 with 100 students per grade; the school will ultimately cover grades 7-12.\n==>\n","completion":" EducationalInstitution"} -{"prompt":" Come Live with Me is a 1941 American romantic comedy film produced and directed by Clarence Brown and starring James Stewart and Hedy Lamarr. Based on a story by Virginia Van Upp the film is about a beautiful Viennese refugee seeking United States citizenship who arranges a marriage of convenience with a struggling writer.\n==>\n","completion":" Film"} -{"prompt":" Philip Sprint is a German footballer who currently plays for Hertha BSC.Sprint made his professional debut for Hertha BSC on 12 August 2012 in a 2. Bundesliga match against FSV Frankfurt coming on in the 50th minute for Marvin Knoll after starting goalkeeper Sascha Burchert had been sent off.\n==>\n","completion":" Athlete"} -{"prompt":" Wave Broadband is a provider of residential business and enterprise class cable TV broadband internet and telephone services on the West Coast currently serving about 400000 customers within communities in western Washington state Oregon Sacramento California and the San Francisco Bay Area. Wave Broadband provides services via their fiber-optic network and uses Northwest Open Access Network as the backbone for most of their service areas in Washington.\n==>\n","completion":" Company"} -{"prompt":" Ficus greiffiana is a species of plant in the Moraceae family. It is found in Argentina Brazil Colombia and Guyana.\n==>\n","completion":" Plant"} -{"prompt":" e-Spirit is a commercial software company that develops and markets the FirstSpirit CMS Web content management system. The company was founded in 1999 in Dortmund Germany and established a US presence in 2011. The company's FirstSpirit CMS is a Java-based offering now in its fifth major release.[citation needed]\n==>\n","completion":" Company"} -{"prompt":" Mungaru Male (English: Pre Monsoon Rain) is a 2006 Kannada language movie directed by Yograj Bhat and produced by E Krishnappa. The film stars Ganesh Pooja Gandhi Anant Nag Padmaja Rao in lead roles.\n==>\n","completion":" Film"} -{"prompt":" Mount Waverley Secondary College is a public secondary school located in the Melbourne suburb of Mount Waverley. The school consists of roughly 1900 students and is one of the largest in the state.The school consists of two campuses (Junior & Senior) both situated on Stephensons Road in Mount Waverley. The Junior site holds years 7 and 8 with year levels 9 to 12 at the Senior Campus. The campuses are a short walking distance apart.\n==>\n","completion":" EducationalInstitution"} -{"prompt":" Jon-Paul Roger JP Pietersen (born 12 July 1986 in Stellenbosch South Africa) is a South African rugby union footballer. He generally plays fullback or wing for the Sharks (in the Super Rugby competition) and the Natal Sharks in the Currie Cup. He played in more than 50 tests for the Springboks.\n==>\n","completion":" Athlete"} -{"prompt":" Yawarmayu (Quechua yawar blood mayu river blood river hispanicized spelling Yahuarmayo) is a river in Peru located in the Puno Region Carabaya Province Ayapata District. It originates near the border of the districts Ayapata and Coasa. Its direction is mainly to the northwest where it meets Inambari River as a right affluent. The confluence is north of the village Yawarmayu (Yahuarmayo).\n==>\n","completion":" NaturalPlace"} -{"prompt":" Mangifera persiciformis or Peach Mango is a species of plant in the Anacardiaceae family. It is endemic to China.\n==>\n","completion":" Plant"} diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/demo.py b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/demo.py deleted file mode 100644 index a0feee377f75a27346e42efdb521674742819db1..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/demo.py +++ /dev/null @@ -1,101 +0,0 @@ -from typing import List - -import symai.core as ai - - -class Demo(ai.Expression): - def __init__(self, value = '', **kwargs) -> None: - super().__init__(value, **kwargs) - - @ai.zero_shot(prompt="Generate a random integer between 0 and 10.", - constraints=[ - lambda x: x >= 0, - lambda x: x <= 10 - ]) - def get_random_int(self) -> int: - pass - - @ai.few_shot(prompt="Generate Japanese names: ", - examples=ai.Prompt(["愛子", "和花", "一郎", "和枝"]), - limit=2, - constraints=[lambda x: len(x) > 1]) - def generate_japanese_names(self) -> list: - pass - - @ai.equals() - def equals_to(self, other) -> bool: - pass - - @ai.compare(operator='>') - def larger_than(self, other) -> bool: - pass - - @ai.case(enum=['angry', 'happy', 'annoyed', 'confused', 'satisfied', 'unknown'], - default='unknown') - def sentiment_analysis(self, text: str) -> str: - pass - - @ai.translate() - def translate(self, text: str, language: str) -> str: - pass - - @ai.zero_shot(default=False, - pre_processors=[ai.ArgsPreProcessor("Are this {} names?"), - ai.ArgsToInputPreProcessor(skip=[0])], - post_processors=[ai.ConfirmToBoolPostProcessor()]) - def is_name(self, language: str, text: str) -> bool: - pass - - @ai.extract() - def extract_pattern(self, pattern: str) -> str: - pass - - @ai.clean() - def clean_text(self, text: str) -> str: - pass - - @ai.summarize() - def summarize_text(self, text: str) -> str: - pass - - @ai.expression() - def evaluate_expression(self, expr: str) -> int: - pass - - @ai.simulate() - def simulate_code(self, code: str) -> str: - pass - - @ai.code() - def generate_code(self, descr: str) -> str: - pass - - @ai.outline() - def create_outline(self, text: str) -> str: - pass - - @ai.compose() - def formulize_text(self, outline: str) -> str: - pass - - @ai.replace() - def replace_substring(self, replace: str, value: str) -> str: - pass - - @ai.rank() - def rank_list(self, measure: str, list_: List, order: str) -> str: - pass - - @ai.notify(subscriber={ - 'email': lambda x: print('Email sent to ...', x), - 'slack': lambda x: print('Slack message sent to ...', x), - 'fruits': lambda x: Exception('Fruits are not supported yet.') - }) - def notify_subscriber(self, *args) -> str: - pass - - def __str__(self) -> str: - return str(self.value) - - def __repr__(self) -> str: - return str(self.value) diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/demo_strategy.py b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/demo_strategy.py deleted file mode 100644 index 27b138eb9027950012d137f8d9371397bd371dc7..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/demo_strategy.py +++ /dev/null @@ -1,67 +0,0 @@ -import logging -from pydoc import locate - -from symai import Expression - - -class Strategy(Expression): - """A base class for implementing strategies.""" - - def __init__(self, *args, **kwargs): - """Initialize the strategy object. - - Args: - *args: Variable length argument list. - **kwargs: Arbitrary keyword arguments. - """ - super().__init__(*args, **kwargs) - self.logger = logging.getLogger(__name__) - - def __new__(self, module: str, *args, **kwargs): - """Create a new instance of the strategy. - - Args: - module (str): The module name of the strategy. - *args: Variable length argument list. - **kwargs: Arbitrary keyword arguments. - - Returns: - Strategy: An instance of the strategy. - - Raises: - NotImplementedError: If __call__ method is not implemented. - """ - module = module.lower() - module = module.replace('-', '_') - self._module = module - self.module_path = f'symai.extended.strategies.{module}' - return Strategy.load_module_class(self.module_path, self._module)(*args, **kwargs) - - def __call__(self, *args, **kwargs): - """Call the strategy. - - Args: - *args: Variable length argument list. - **kwargs: Arbitrary keyword arguments. - - Raises: - NotImplementedError: If not overridden by child class. - """ - raise NotImplementedError() - - @staticmethod - def load_module_class(module_path, class_name): - """Load a module class dynamically. - - Args: - module_path (str): The path of the module. - class_name (str): The name of the class. - - Returns: - class: The loaded module class. - - Raises: - AttributeError: If the module or class is not found. - """ - module_ = locate(module_path) - return getattr(module_, class_name) \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/docs.py b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/docs.py deleted file mode 100644 index 1389eca31f1e56129fbd91a3fba9ad46c5b801c3..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/docs.py +++ /dev/null @@ -1,111 +0,0 @@ -import symai as ai -from symai.post_processors import StripPostProcessor -from symai.pre_processors import PreProcessor -from symai.symbol import Expression, Symbol - -DOC_CONTEXT = '''General Python Template example: - """_summary_ - - Args: - prompt (_type_, optional): _description_. Defaults to 'Summarize the content of the following text:\n'. - constraints (List[Callable], optional): _description_. Defaults to []. - default (object, optional): _description_. Defaults to None. - pre_processors (List[PreProcessor], optional): _description_. Defaults to [TextMessagePreProcessor()]. - post_processors (List[PostProcessor], optional): _description_. Defaults to [StripPostProcessor()]. - - Returns: - _type_: _description_ - """ - - Method Signature Example: - def summarize(prompt: str = 'Summarize the content of the following text:\n', - constraints: List[Callable] = [], - default: object = None, - pre_processors: List[PreProcessor] = [TextMessagePreProcessor()], - post_processors: List[PostProcessor] = [StripPostProcessor()], - **kwargs): - return few_shot(prompt, - examples=[], - constraints=constraints, - default=default, - limit=1, - pre_processors=pre_processors, - post_processors=post_processors, - **kwargs) - - Documentation Example Text: - """Summarizes the content of a text. - - Args: - prompt (str, optional): The prompt describing the task. Defaults to 'Summarize the content of the following text:\n'. - constraints (List[Callable], optional): A list of constrains applied to the model output to verify the output. Defaults to []. - default (object, optional): The default value to be returned if the task cannot be solved. Defaults to None. Alternatively, one can implement the decorated function. - pre_processors (List[PreProcessor], optional): A list of pre-processors to be applied to the input and shape the input to the model. Defaults to None. - post_processors (List[PostProcessor], optional): A list of post-processors to be applied to the model output and before returning the result. Defaults to [StripPostProcessor()]. - - Returns: - str: The summary of the text. - """ - ''' - - -class DocsPreProcessor(PreProcessor): - def __call__(self, argument): - return 'Method Signature:\n{}\nDocumentation Text:'.format(str(argument.prop.instance)) - - -class Docs(Expression): - @property - def static_context(self): - return DOC_CONTEXT - - def forward(self, sym: Symbol, *args, **kwargs): - @ai.few_shot(prompt="Create only Python style documentation text based on the given template and shown in the example with the provided function signature:", - examples=[], - pre_processors=[DocsPreProcessor()], - post_processors=[StripPostProcessor()], **kwargs) - def _func(_) -> str: - pass - return Docs(_func(Docs(sym))) - - -CPP_DOC_CONTEXT = """Documentation example for a C++ code snippet: - -Method: -void putbytes(const char* s, int len); - -Documentation text: -/** @brief Prints the string s, starting at the current - * location of the cursor. - * - * If the string is longer than the current line, the - * string should fill up the current line and then - * continue on the next line. If the string exceeds - * available space on the entire console, the screen - * should scroll up one line, and then the string should - * continue on the new line. If '\n', '\r', and '\b' are - * encountered within the string, they should be handled - * as per putbyte. If len is not a positive integer or s - * is null, the function has no effect. - * - * @param s The string to be printed. - * @param len The length of the string s. - * @return Void. - */ -""" - - -class CppDocs(Expression): - @property - def static_context(self): - return CPP_DOC_CONTEXT - - def forward(self, sym: Symbol, *args, **kwargs): - @ai.few_shot(prompt="Create only C++ style documentation text based on the given template and shown in the example with the provided function signature:", - examples=[], - pre_processors=[DocsPreProcessor()], - post_processors=[StripPostProcessor()], **kwargs) - def _func(_) -> str: - pass - return CppDocs(_func(Docs(sym))) - diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/einsteins_puzzle.txt b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/einsteins_puzzle.txt deleted file mode 100644 index de040d1f802452c032e7cc8a2881bb4c4e3560d2..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/einsteins_puzzle.txt +++ /dev/null @@ -1,19 +0,0 @@ -Let us assume that there are five houses of different colors next to each other on the same road. In each house lives a man of a different nationality. Every man has his favorite drink, his favorite brand of cigarettes, and keeps pets of a particular kind. - -The Englishman lives in the red house. -The Swede keeps dogs. -The Dane drinks tea. -The green house is just to the left of the white one. -The owner of the green house drinks coffee. -The Pall Mall smoker keeps birds. -The owner of the yellow house smokes Dunhills. -The man in the center house drinks milk. -The Norwegian lives in the first house. -The Blend smoker has a neighbor who keeps cats. -The man who smokes Blue Masters drinks bier. -The man who keeps horses lives next to the Dunhill smoker. -The German smokes Prince. -The Norwegian lives next to the blue house. -The Blend smoker has a neighbor who drinks water. - -The question to be answered is: Who keeps fish? \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/file.json b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/file.json deleted file mode 100644 index 6509468a99ef3a26258fc5c28aa03e43647ff71f..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/file.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "name": "Test Decorators", - "type": "python", - "request": "launch", - "program": "${workspaceFolder}/tests/test_decorators.py", - "console": "integratedTerminal", - "justMyCode": true, - "env": { - "PYTHONPATH": "${workspaceFolder}", - "OPENAI_API_KEY": "", - "CUDA_VISIBLE_DEVICES": "1" - } - } - ] -} \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/lean.py b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/lean.py deleted file mode 100644 index f971e562ecaf1c8d2a87ee01150732960c6fee0c..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/lean.py +++ /dev/null @@ -1,20 +0,0 @@ -from symai.backend.engines.lean.engine_lean4 import LeanEngine -# Example usage -if __name__ == "__main__": - # Initialize LeanEngine - engine = LeanEngine() - - # Sample Lean code - code = ''' - theorem and_commutative (A B : Prop) : A ∧ B → B ∧ A := - fun h : A ∧ B => ⟨h.right, h.left⟩dsdsdds - ''' - - # Execute the Lean code - print("Running LeanEngine with a sample Lean theorem...") - results, metadata = engine.forward(code) - - # Check if results are valid and print the output - if results: - print("Results:", results[0].value['output']) - print("Metadata:", metadata) diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/news.py b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/news.py deleted file mode 100644 index 1feff9b672d646472ba9e6013f017c3143ced3ba..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/news.py +++ /dev/null @@ -1,98 +0,0 @@ -from symai import * -from symai.components import * - - -HEADER_STYLE_DESCRIPTION = """Design a web app with HTML, CSS and inline JavaScript. -Use dark theme and best practices for colors, text font, etc. -Use Bootstrap for styling. -Do NOT remove the {{placeholder}} tag and do NOT add new tags into the body!""" - -HTML_TEMPLATE = """ - - - - - News - - - - {{placeholder}} - - - -""" - -HTML_STREAM_STYLE_DESCRIPTION = f"""Style the elements according to the bootstrap library. -Create sections, listings, paragraphs, and headings based on the news data. -Add emphasis and animations to elements if appropriate. Organize the content in tiles or cards. -Use best practices for colors, text font, etc. and try to make the web app look professional and modern. -Output the html output within a ```html\n ... \n``` code block. -Do not remove any content from the news data. -Assume the elements are inside the body `placeholder` tag of the following HTML template: -{HTML_TEMPLATE}""" - -class News(Expression): - """The `News` class sub-classes `Expression` and provides a way to fetch and render news from a given url. It uses a `Stream` object to process the news data, with a sequence of `Clean`, `Translate`, `Outline`, and `Compose` expressions. - It also defines a `Style` for the header, and a `Symbol` for the HTML templates. - """ - def __init__(self, url: str, pattern: str, filters: List[Expression] = [], render: bool = False, **kwargs): - """The `News` class constructor requires three arguments - `url`, `pattern` and `filters`. - * `url` is a `str` containing the url to fetch the news from. - * `pattern` is a `str` containing the regex pattern to be used to match the news. - * `filters` is a `List[Expression]` containing any additional filters that should be applied to the news data. - It defaults to an empty list if not specified. - The `News` class also has an optional `render` argument which is a `bool` indicating whether the news should be rendered. It defaults to `False` if not specified. - """ - super().__init__(**kwargs) - self.url = url - self.crawler = Interface('selenium') - self.pattern = pattern - self.render_ = render - filters = filters if isinstance(filters, List) or isinstance(filters, tuple) else [filters] - self.data_stream = Stream(Sequence( - Clean(), - Translate(), - Outline(), - *filters, - Compose(f'Compose a comprehensive news article. Group all facts that belong together topics-wise:\n'), - )) - self.html_stream = Stream(Sequence( - Template(template=HTML_TEMPLATE), - Style(description=HTML_STREAM_STYLE_DESCRIPTION, - libraries=['https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css', - 'https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js', - 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js']), - )) - self.post_processors = ProcessorPipeline([StripPostProcessor(), CodeExtractPostProcessor()]) - self.writer = FileWriter('tmp/news.html') - - def render(self, sym: Symbol, **kwargs) -> Symbol: - """The `render` method takes a `Symbol` as an argument and returns a `Symbol` containing the rendered news. - It first sets the `html_template_seq` property of the `html_stream` to the result of applying the `header_style` to the `html_template`. - It then iterates through the `data_stream` and collects the strings resulting from each expression. - These strings are combined into a single `Symbol` object which is then clustered. - Finally, the `render` method applies the `html_template` to the clustered `Symbol` and returns the result. - """ - res = '\n'.join([str(s) for s in self.html_stream(sym, **kwargs)]) - res = self.post_processors(str(res), None) - res = Symbol(str(HTML_TEMPLATE).replace('{{placeholder}}', res)) - self.writer(res) - return res - - def forward(self, **kwargs) -> Symbol: - """The `forward` method is used to fetch and process the news data. - It first calls the `fetch` method with the `url` and `pattern` arguments. - It then iterates through the `data_stream` and collects the `Symbol` object resulting from each expression. - These `Symbol` objects are then combined into a single `Symbol` object which is then mapped. - If `render` is `False`, the mapped `Symbol` is returned. Otherwise, the `render` method is called with the `Symbol` and the resulting `Symbol` is returned. - """ - res = self.crawler(url=self.url, pattern=self.pattern) - vals = [] - for news in self.data_stream(str(res), **kwargs): - if news is not None and len(str(news).strip()) > 0: - vals.append(str(news)) - res = Symbol(vals).cluster() - sym = res.map() - if not self.render_: - return sym - return self.render(sym, **kwargs) diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/paper.pdf b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/paper.pdf deleted file mode 100644 index 5f7c692746e8a9b8113fcd6b9d64fea7aaa22de4..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/paper.pdf +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7f0bb48c23dd840c4772ba02f2b72289643d9654717922c6ada74454591f35d8 -size 762191 diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/paper.py b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/paper.py deleted file mode 100644 index 9976d050cac805e61334ebfa1e0578e4054e882d..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/paper.py +++ /dev/null @@ -1,66 +0,0 @@ -from symai import * -from symai.components import * - - -HEADER_STYLE_DESCRIPTION = """Design a web app with HTML, CSS and inline JavaScript. -Use dark theme and best practices for colors, text font, etc. -Use Bootstrap for styling. -Do NOT remove the {{placeholder}} tag and do NOT add new tags into the body!""" - -HTML_TEMPLATE = """ - - - - - Paper Summary - - - - {{placeholder}} - -""" - -HTML_STREAM_STYLE_DESCRIPTION = """Style the elements according to the bootstrap library. -Replace the list items with a summary title and the item text. -Add highlighting animations. -Use best practices for colors, text font, etc.""" - - -class Paper(Expression): - def __init__(self, path: str, filters: List[Expression] = [], **kwargs): - super().__init__(**kwargs) - self.path = path - filters = filters if isinstance(filters, List) or isinstance(filters, tuple) else [filters] - self.data_stream = Stream(Sequence( - Clean(), - Translate(), - *filters, - Compose(f'Write a paper summary. Keep all information with the corresponding citations:\n'), - )) - self.header_style = Style(description=HEADER_STYLE_DESCRIPTION, - libraries=['https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css', - 'https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js', - 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js']) - - self.html_template = Symbol(HTML_TEMPLATE) - self.html_template_seq = Template() - self.html_stream = Stream( - Sequence( - self.html_template_seq, - Style(description=HTML_STREAM_STYLE_DESCRIPTION) - ) - ) - - def forward(self, **kwargs) -> Symbol: - res = self.open(self.path, **kwargs) - data = '' - template = self.header_style(self.html_template) - paragraphs = [] - for section in self.data_stream(res): - key = section.unique(paragraphs) - paragraphs.append(str(key)) - self.html_template_seq.template_ = str(template) - kwargs['dynamic_context'] = f'Context: Create a summary paragraph about {str(key)}\n' - data += '\n'.join([str(s) for s in self.html_stream(section, **kwargs)]) - res = Symbol(str(template).replace('{{placeholder}}', data)) - return res diff --git a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/sql.py b/symbolicai-main/symbolicai-main/legacy/notebooks/examples/sql.py deleted file mode 100644 index 4e6becbfacb272f35f82dbc7a59ce7497122499f..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/notebooks/examples/sql.py +++ /dev/null @@ -1,68 +0,0 @@ -import symai as ai -from symai.post_processors import StripPostProcessor, CodeExtractPostProcessor -from symai.pre_processors import PreProcessor -from symai.symbol import Expression, Symbol - - -SQL_CONTEXT = """[Description] -The following statements describe the Structured Query Language (SQL): - -Commonly used SQL commands with examples: -Most SQL commands are used with operators to modify or reduce the scope of data operated on by the statement. Some commonly used SQL commands, along with examples of SQL statements using those commands, follow. - -SQL SELECT. The SELECT command is used to get some or all data in a table. SELECT can be used with operators to narrow down the amount of data selected. -SQL CREATE. The CREATE command is used to create a new SQL database or SQL table. Most versions of SQL create a new database by creating a new directory, in which tables and other database objects are stored as files. -SQL DELETE. The DELETE command removes rows from a named table. -The CREATE TABLE command is used create a table in SQL. - -[Examples] -// Select the title, author and publication date columns from a table named catalog. -SELECT title, author, pub_date -FROM catalog -WHERE pub_date = 2021; - -// The following CREATE DATABASE statement creates a new SQL database named Human_Resources: -SQL: CREATE DATABASE Human_Resources; - -// The following statement creates a table named Employees that has three columns: employee_ID, last_name and first_name, with the first column storing integer (int) data and the other columns storing variable character data of type varchar and a maximum of 255 characters. -SQL: CREATE TABLE Employees ( - employee_ID int, - last_name varchar(255), - first_name varchar(255) -); - -// All records of employees with the last name Smithee are deleted: -SQL: DELETE FROM Employees WHERE last_name='Smithee'; - -[IMPORTANT] -ALWAYS RETURN ONLY THE ENTIRE SQL STATEMENTS, NOT PARTIAL RESULT LIKE {} ... OR OTHER PLACEHOLDER! -NOT VALID: -{} limit 1 -VALID: -SELECT * FROM table limit 1 - -[Last Example] --------------- -""" - - -class SQLPreProcessor(PreProcessor): - def __call__(self, argument): - return '// {} SQL:'.format(str(argument.prop.instance)) - - -class SQL(Expression): - @property - def static_context(self): - return SQL_CONTEXT - - def forward(self, sym: Symbol, *args, **kwargs): - @ai.few_shot(prompt="Generate queries based on the SQL domain specific language description\n", - examples=[], - pre_processors=[SQLPreProcessor()], - post_processors=[StripPostProcessor(), CodeExtractPostProcessor()], - stop=[';'], **kwargs) - def _func(_) -> str: - pass - return SQL(_func(SQL(sym))) - diff --git a/symbolicai-main/symbolicai-main/legacy/old/test_backend.py b/symbolicai-main/symbolicai-main/legacy/old/test_backend.py deleted file mode 100644 index 5060f8bb881d43e92dbe95b01bfa6926ecc52f70..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/old/test_backend.py +++ /dev/null @@ -1,26 +0,0 @@ -import unittest - -from symai import Expression, Symbol -from symai.components import Template - -Expression.command(time_clock=True) - - -class TestBackend(unittest.TestCase): - def test_index(self): - expr = Expression() - s1 = Symbol('Hello World!').zip() - s2 = Symbol('I like cookies!').zip() - expr.add(s1, index_name='defaultindex') - expr.add(s2, index_name='defaultindex') - res = expr.get(Symbol('hello').embed().value).ast() - self.assertTrue('Hello World!' in res, res) - - def test_html_template(self): - template = Template() - res = template(Symbol('Create a table with two columns (title, price).', 'data points: Apple, 1.99; Banana, 2.99; Orange, 3.99')) - self.assertTrue('' in res, res) - - -if __name__ == '__main__': - unittest.main() diff --git a/symbolicai-main/symbolicai-main/legacy/old/test_components.py b/symbolicai-main/symbolicai-main/legacy/old/test_components.py deleted file mode 100644 index 9fadc9b35d7cbb9ab18b67277f140d35fbd7ed3e..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/old/test_components.py +++ /dev/null @@ -1,166 +0,0 @@ -import unittest - -import torch -import numpy as np -import symai as ai -from symai.components import * - - -class TestComponents(unittest.TestCase): - def test_similarity_classification(self): - classes = [ - 'Bought a new mug.', - 'I wish I had a new mug.', - 'I bought a new mug.' - ] - f = SimilarityClassification(classes, in_memory=True) - - x = 'I bought a new mug.' - y = f(x).value - self.assertEqual(x, y) - - def test_primitives(self): - # concatenation with space - res = Symbol('hello') | Symbol('world') - assert res.value == 'hello world', res - # concatenation without space - res = Symbol('hello') & Symbol('world') - assert res.value == 'helloworld', res - # neuro-symbolic engine calls - res = Symbol('I hate you now.') - 'hate' + 'love' - assert res.value == 'I love you now.', res - # type specific calls - res = Symbol(np.array([1,2,3])) + np.array([4,5,6]) - assert np.all(res == np.array([5, 7, 9])), res - # fuzzy computations - res = Symbol('five') + 5 - assert res.int() == 10, res - # fuzzy comparisons - res = Symbol('five') > 4 - assert res, res - # fuzzy comparison - res = 'wolf' in Symbol('Wolfspitz') - assert res, res - # direct type comparison - res = 5 in Symbol(np.array([1, 2, 3, 4, 5])) - assert res, res - # NOT True => by default disable primitive iteration on nesy engine - res = 'five' in Symbol(np.array([1, 2, 3, 4, 5])) - assert not res, res - # enable primitive iteration on nesy engine - res = 'five' in Symbol(np.array([1, 2, 3, 4, 5]), semantic=True) - assert res, res - sym = Symbol("Hi there, my name is Marius and I have a question: If I integrate two normal distributions do I ...?") - assert sym['name'] == "Marius" - - def test_symbia_capabilities(self): - f = InContextClassification(ai.prompts.SymbiaCapabilities()) - - x = Symbol('How could I solve an elliptical equation?') - y = f(x) - self.assertTrue('[WORLD-KNOWLEDGE]' in y.value, y) - - x = Symbol('What is 10 choose 5?') - y = f(x) - self.assertTrue('[SYMBOLIC]' in y.value, y) - - x = Symbol('What where who, nevermind!') - y = f(x) - self.assertTrue('[DK]' in y.value, y) - - x = Symbol('Give me some flights between Timisoara and Linz.') - y = f(x) - self.assertTrue('[SEARCH]' in y.value, y) - - x = Symbol('What does sdfjklas mean?') - y = f(x) - self.assertTrue('[DK]' in y.value, y) - - x = Symbol('Find me a recipe for vegan lasagna.') - y = f(x) - self.assertTrue('[SEARCH]' in y.value, y) - - x = Symbol('Extract all blog post titles from this website: https://exampleblog.com/') - y = f(x) - self.assertTrue('[CRAWLER]' in y.value, y) - - x = Symbol('Transcribe this podcast episode into text: ~/Documents/show.mp3') - y = f(x) - self.assertTrue('[SPEECH-TO-TEXT]' in y.value, y) - - x = Symbol('Generate an image of a snowy mountain landscape.') - y = f(x) - self.assertTrue('[TEXT-TO-IMAGE]' in y.value, y) - - x = Symbol('Can you read the text from this image of a sign? File: /home/username/Pictures/tokyo.jpg') - y = f(x) - self.assertTrue('[OCR]' in y.value, y) - - x = Symbol("Find the author's perspective on artificial intelligence in this article. File: /home/username/Documents/AI_Article.pdf") - y = f(x) - self.assertTrue('[RETRIEVAL]' in y.value, y) - - x = Symbol('I have to go now, bye!') - y = f(x) - self.assertTrue('[EXIT]' in y.value, y) - - x = Symbol('Can you tell me more about your skills?') - y = f(x) - self.assertTrue('[HELP]' in y.value, y) - - x = Symbol('What can you do for me?') - y = f(x) - self.assertTrue('[HELP]' in y.value, y) - - def test_indexer(self): - indexer = Indexer(index_name='dataindex') - indexer('This is a test!') # upsert - index = indexer() - rsp = index('Is there a test?') # retrieve - self.assertTrue('confirmation that there is a test' in rsp) - - - def test_symbol_typing(self): - sym = Symbol({1: 'a', 2: 'b', 3: 'c'}) - assert sym.value_type == dict - sym = Symbol([1, 2, 3]) - assert sym.value_type == list - sym = Symbol('abc') - assert sym.value_type == str - sym = Symbol(1) - assert sym.value_type == int - sym = Symbol(1.0) - assert sym.value_type == float - sym = Symbol(True) - assert sym.value_type == bool - sym = Symbol(Symbol('test')) - assert sym.value_type == str - sym.value == 'test' - sym = Symbol(Symbol(1)) - assert sym.value_type == int - sym.value == 1 - sym = Symbol(Symbol(Symbol(1))) - assert sym.value_type == int - assert sym.value == 1 - sym = Symbol([Symbol(1), Symbol(2), Symbol(3)]) - assert sym.value_type == list - assert sym.value == [1, 2, 3] - sym = Symbol(Symbol([1, 2, 3])) - assert sym.value_type == list - assert sym.value == [1, 2, 3] - sym = Symbol(Symbol(Symbol([1, 2, 3]))) - assert sym.value_type == list - assert sym.value == [1, 2, 3] - sym = Symbol({Symbol(1): Symbol(Symbol([1, 2, 4])), Symbol(3): Symbol(4)}) - assert sym.value_type == dict - assert sym.value == {1: [1, 2, 4], 3: 4} - arr = np.array(Symbol([Symbol(1), Symbol(3), Symbol(4)])) - assert np.all(np.array([1, 3, 4])) - tensor = torch.tensor(Symbol([Symbol(1), Symbol(3), Symbol(4)])) - assert torch.all(torch.tensor([1, 3, 4])) - tensor = torch.tensor(Symbol([Symbol(1), Symbol(3), Symbol(4)]), dtype=torch.float32) - assert torch.all(torch.tensor([1, 3, 4], dtype=torch.float32)) - - -if __name__ == '__main__': - unittest.main() diff --git a/symbolicai-main/symbolicai-main/legacy/old/test_composition.py b/symbolicai-main/symbolicai-main/legacy/old/test_composition.py deleted file mode 100644 index fce7460fb69acb02a6e46321257eaeed7af6370e..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/old/test_composition.py +++ /dev/null @@ -1,834 +0,0 @@ -import os -import unittest - -import numpy as np - -# from notebooks.examples.news import News -# from notebooks.examples.paper import Paper -# from notebooks.examples.sql import SQL -from symai import * -from symai.chat import SymbiaChat -from symai.extended import * -from symai.components import * - -# for debugging -# attention this constantly overwrites the keys config file -#os.environ['OPENAI_API_KEY'] = '' - - -Expression.command(time_clock=True) - - -class TestComposition(unittest.TestCase): - - def test_result_clean(self): - crawler = Interface('selenium') - sym = crawler(url='https://donate.wikimedia.org/w/index.php?title=Special:LandingPage&country=AT&uselang=en&utm_medium=sidebar&utm_source=donate&utm_campaign=C13_en.wikipedia.org') - self.assertIsNotNone(sym) - res = sym.clean() - self.assertIsNotNone(res) - print(res) - - def test_map_to_language(self): - sym = Symbol(['Hi', 'hello', 'buna ziua', 'hola', 'Bonjour', 'Guten Tag']) - res = sym.dict('to language') - self.assertTrue('English' in res, res) - - def test_add_and_equals(self): - res = Symbol('Hello') + Symbol('World') - self.assertTrue(res == 'Hello World', res) - res += "." - self.assertTrue(res == 'Hello World!', res) - self.assertTrue(res != 'Apples', res) - - sym = Symbol(1) + Symbol(2) - self.assertTrue(sym == 3, sym) - - def test_sub_and_contains(self): - res = (Symbol('Hello my friend') - Symbol('friend')) + 'enemy' - self.assertTrue('enemy' in res, res) - - def test_compare(self): - res = Symbol(10) > Symbol(5) - self.assertTrue(res, res) - res = Symbol(5) >= Symbol('5') - self.assertTrue(res, res) - res = Symbol(1) < Symbol('five') - self.assertTrue(res, res) - res = Symbol(1) <= Symbol('one') - self.assertTrue(res, res) - res = Symbol(2) < Symbol(1) - self.assertTrue(not res, res) - - def test_iterator(self): - res = Symbol('Hello World') - a = '' - for item in res: - a = item - self.assertTrue(a == 'World', a) - a = '' - for item in reversed(res): - a = item - self.assertTrue(a == 'Hello', a) - - def test_filter(self): # TODO: success rate not 100% - sym = Symbol('Physics, Sports, Mathematics, Music, Art, Theater, Writing') - res = sym.filter('science related subjects') - self.assertTrue(res == 'Sports, Music, Art, Theater, Writing', res) - - def test_modify(self): - sym = Symbol('Mathematic, Physics, Sports, Music, Art, Theater, Writing') - res = sym.modify('to lower case') - self.assertTrue(res == 'mathematic, physics, sports, music, art, theater, writing', res) - - def test_get_set_item(self): - sym = Symbol({'name': 'John', 'age': 30}) - sym['name'] = 'Jane' - self.assertTrue(sym['name'] == 'Jane') - self.assertTrue(30 in sym, sym) - del sym['age'] - self.assertTrue(30 not in sym, sym) - - def test_negate(self): - sym = Symbol('I hate you!') - res = -sym - self.assertTrue('I do not hate you' in res, res) - res = -res - self.assertTrue('I hate you' in res, res) - - def test_convert(self): - sym = Symbol("There are two ways to identify classes. First, you can identify them using their parent module, something like abc.ABCMeta. To do this, start with the sys.modules dictionary, and look up modules and submodules (that is: look up 'abc'). ") - res = sym.convert('a song about classes') - self.assertIsNotNone(res) - - def test_transcribe(self): - sym = Symbol("""This code defines a custom PyTorch model for semantic segmentation, which is a subtype of image segmentation where each pixel in an image is classified into one of several predefined classes. The custom model is called "CustomSegformerForSemanticSegmentation" and it is based on the "Segformer" model from the "transformers" library. - -In the _init_ function, the custom model takes in a configuration object (config) and a pre-trained Segformer model (seg_model). It initializes the parent SegformerPreTrainedModel class and then assigns the seg_model to an attribute called segformer and creates an instance of SegformerDecodeHead with the same config object.)""") - res = sym.transcribe('to markdown text with classed and variables using ` format') - self.assertIsNotNone(res) - - def test_input(self): # TODO: not working from IDE - sym = Expression('Hello World') - res = sym.input('What is your name?') - self.assertIsNotNone("Johnny" == res, res) - - def test_logic(self): - res = Symbol('the horn only sounds on Sundays') & Symbol('I hear the horn') - self.assertTrue('it is Sunday' in res, res) - res = Symbol('the horn sounds on Sundays') | Symbol('the horn sounds on Mondays') - self.assertTrue('Sundays or Mondays' in res, res) - res = Symbol('The duck quaks.') ^ Symbol('The duck does not quak.') - self.assertTrue('The duck quaks.' in res, res) - - def test_clean(self): - sym = Symbol('Hello *&&7amp;;; \t\t\t\nWorld').clean() - self.assertTrue('Hello World' == sym) - - def test_summarize(self): - sym = Symbol( - """News is information about current events. This may be provided through many different media: word of mouth, printing, postal systems, broadcasting, electronic communication, or through the testimony of observers and witnesses to events. News is sometimes called "hard news" to differentiate it from soft media. - Common topics for news reports include war, government, politics, education, health, the environment, economy, business, fashion, entertainment, and sport, as well as quirky or unusual events. Government proclamations, concerning royal ceremonies, laws, taxes, public health, and criminals, have been dubbed news since ancient times. Technological and social developments, often driven by government communication and espionage networks, have increased the speed with which news can spread, as well as influenced its content.""" - ) - res = sym.summarize() - self.assertTrue(len(res) < len(sym)) - - def test_compose_manual(self): - sym = Symbol(['DeepMind released new article', 'Uber is working on self-driving cars', 'Google updates search engine']) - res = sym.compose() - self.assertIsNotNone(res) - - def test_replace(self): - sym = Symbol('I hate to eat apples') - res = sym.replace('hate', 'love') - self.assertTrue('I love to eat apples' in res, res) - - def test_insert(self): - sym = Symbol('I love to eat apples') - res = sym.include('and bananas') - self.assertTrue('I love to eat apples and bananas' in res, res) - - def test_insert_lshift(self): - sym = Symbol('I love to eat apples') - res = sym << 'and bananas' - self.assertTrue('I love to eat apples and bananas' in res, res) - - def test_insert_rshift(self): - sym = Symbol('I love to eat apples') - res = 'and bananas' >> sym - self.assertTrue('I love to eat apples and bananas' in res, res) - - def test_html_template(self): - template = Template() - res = template(Symbol('Create a table with two columns (title, price).', 'data points: Apple, 1.99; Banana, 2.99; Orange, 3.99')) - self.assertTrue('
' in res, res) - - def test_rank(self): - sym = Symbol('a, b, c, d, e, f, g') - res = sym.rank(measure='alphabetical', order='descending') - self.assertTrue(res == 'g, f, e, d, c, b, a') - - def test_rank2(self): - sym = Symbol(np.array([1, 2, 3, 4, 5, 6, 7])) - res = sym.rank(measure='numerical', order='descending') - self.assertTrue(res == '7, 6, 5, 4, 3, 2, 1') - - def test_extract(self): - sym = Symbol('I have an iPhone from Apple. And it is not cheap. I love to eat bananas, mangos, and oranges. My hobbies are playing football and basketball.') - res = sym.extract('fruits') - check = Symbol(['bananas', 'mangos', 'oranges']) - self.assertTrue('apple' not in res, res) - self.assertTrue(check == res, res) - res = sym.replace('one iPhone', 'two iPhones') - self.assertTrue('two iPhones' in res, res) - res = res.query('count iPhones and fruits') - self.assertTrue('two iPhones and three fruits' in res, res) - - def test_extract_tokens(self): - sym = Symbol("""Exception: Failed to query GPT-3 after 3 retries. Errors: [InvalidRequestError(message="This model's maximum context length is 4097 tokens, however you requested 7410 tokens (2988 in your prompt; 4422 for the completion). Please reduce your prompt; or completion length.", - param=None, code=None, http_status=400, request_id=None)]""") - res = sym.extract('requested tokens').cast(int) - self.assertTrue(7410 == res, res) - - def test_correct_max_context_size(self): - sym = Symbol("""Exception: Failed to query GPT-3 after 3 retries. Errors: [InvalidRequestError(message="This model's maximum context length is 4097 tokens, however you requested 7410 tokens (2988 in your prompt; 4422 for the completion). Please reduce your prompt; or completion length.", - param=None, code=None, http_status=400, request_id=None)]""") - res = sym.compose() - self.assertIsNotNone(res) - - def test_equality(self): - sym = Symbol('3.1415...') - self.assertTrue(sym == np.pi) - - def test_expression(self): - expression = Interface('wolframalpha') - res = expression('1 + 2') - self.assertTrue(res == 3) - - res = expression('2 ^ 2') - self.assertTrue(res == 4) - - def test_wolframalpha_expression(self): - expr = Interface('wolframalpha') - res = expr('x^2 + 2x + 1, x = 4') - self.assertTrue(res == 25, res) - - res = expr('How is the weather today in L.A.?') - self.assertIsNotNone(res, res) - - def test_analyze(self): - sym = Symbol('a = 9 + 2') - expr = Try(expr=Execute()) - res = expr(sym) - self.assertTrue(11 == res['locals']['a'], res) - - def test_analyze_fail_correct(self): - sym = Symbol('a = int("3,")') - expr = Try(expr=Execute()) - res = expr(sym) - self.assertTrue(3 == res['locals']['a'], res) - - def test_analyze_fail_correct_ftry(self): - sym = Symbol('a = int("3,"). + 2') - res = sym.fexecute(retries=2) - self.assertTrue(5 == res['locals']['a'], res['locals']) - - def test_json_parser(self): - err = """During handling of the above exception, another exception occurred: - -Traceback (most recent call last): - File "/Users/xpitfire/workspace/symbolicai/tests/test_composition.py", line 245, in test_json_parser - res = parser(code) - ^^^^^^^^^^^^ - File "/Users/xpitfire/workspace/symbolicai/symai/symbol.py", line 1640, in __call__ - self._value = self.forward(*args, **kwargs) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/Users/xpitfire/workspace/symbolicai/symai/components.py", line 413, in forward - res = self.fn(sym, **kwargs) - ^^^^^^^^^^^^^^^^^^^^^^ - File "/Users/xpitfire/workspace/symbolicai/symai/symbol.py", line 1640, in __call__ - self._value = self.forward(*args, **kwargs) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/Users/xpitfire/workspace/symbolicai/symai/components.py", line 51, in forward - return sym.ftry(self.expr, retries=self.retries, **kwargs) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/Users/xpitfire/workspace/symbolicai/symai/symbol.py", line 1529, in ftry - sym = code.correct(context=context, - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/Users/xpitfire/workspace/symbolicai/symai/symbol.py", line 1111, in correct - return self.sym_return_type(_func(self)) - ^^^^^^^^^^^ - File "/Users/xpitfire/workspace/symbolicai/symai/core.py", line 46, in wrapper - return few_shot_func(instance, - ^^^^^^^^^^^^^^^^^^^^^^^ - File "/Users/xpitfire/workspace/symbolicai/symai/functional.py", line 232, in few_shot_func - return _process_query(engine=neurosymbolic_engine, - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/Users/xpitfire/workspace/symbolicai/symai/functional.py", line 173, in _process_query - raise e # raise exception if no default and no function implementation - ^^^^^^^ - File "/Users/xpitfire/workspace/symbolicai/symai/functional.py", line 149, in _process_query - rsp, metadata = _execute_query(engine, argument) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/Users/xpitfire/workspace/symbolicai/symai/functional.py", line 81, in _execute_query - if not constraint(rsp): - ^^^^^^^^^^^^^^^ - File "/Users/xpitfire/workspace/symbolicai/symai/constraints.py", line 21, in __call__ - raise ConstraintViolationException(f"Invalid JSON: ```json\n{input.value}\n```\n{e}")""" - - - parser = JsonParser("Extract all error messages into a json format. I am only interested in the `message` and if there are multiple errors, extract a list of messages.:", {'errors': [ - {'message': ''}, - {'message': ''}, -]}) - res = parser(err) - self.assertTrue('methods' in str(res), res) - - def test_execute(self): - sym = Symbol(""" -def test_inception(): - from symai import Symbol - sym = Symbol('Hello World') - res = sym.translate('Spanish') - return 'Hola Mundo' in res.value, res -val, res = test_inception() -test = 'it works' -""") - res = sym.execute() - self.assertTrue('test' in res.raw.locals) - self.assertTrue(res.raw.locals.test == 'it works') - self.assertTrue('val' in res.raw.locals) - self.assertTrue(type(res.raw.locals.val) == bool) - self.assertTrue('res' in res.raw.locals) - self.assertTrue(res.raw.locals.res == 'Hola Mundo') - self.assertTrue(res.raw.locals.val) - - def test_execute_pseudo_code(self): # TODO: check how to fix SyntaxError: invalid syntax - expr = Expression() - code = expr.open('examples/a_star.txt') - - run = Try(Stream(Sequence( - Convert(format='Python'), - Try(expr=Execute()) - ))) - - res = list(run(code)) - self.assertIsNotNone(res) - self.assertTrue('A_Star' in res['locals']) - - def test_list(self): - sym = Symbol(""" -modified: symai/backend/driver/webclient.py -modified: symai/backend/engine_gptX_completion.py -modified: symai/backend/engine_userinput.py -modified: symai/core.py -modified: symai/expressions.py -modified: symai/functional.py -modified: symai/pre_processors.py -modified: symai/prompts.py -modified: tests/test_composition.py -""") - cnt = 0 - iter_ = sym.list('file path') - for res in iter_: - cnt += 1 - self.assertTrue(cnt == 9, cnt) - - def test_foreach(self): - sym = Symbol('a, b, c, d, e, f, g') - res = sym.foreach(condition='letters', apply='append index a:0, ...') - self.assertTrue(res == 'a:0, b:1, c:2, d:3, e:4, f:5, g:6', res) - - def test_translate(self): - sym = Symbol('Hello World') - res = sym.translate('Spanish') - self.assertTrue('Hola Mundo' == res, res) - self.assertTrue('Hello World' in sym, sym) # check if original symbol is not changed - - def test_choice(self): - sym = Symbol("Generate a meme about a cat.") - res = sym.choice(['memes', 'politics', 'sports', 'unknown'], default='unknown') - self.assertTrue('memes' in res, res) - - def test_query(self): - sym = Symbol() - res = sym.query('What is the capital of Austria?') - self.assertTrue('Vienna' == res, res) - - def test_query_context(self): - sym = Symbol('The Semantic Web is rapidly evolving, offering the potential to revolutionize our online experience. Its three main technical standards are RDF, SPARQL and OWL, which are used to distinguish its applications. The contemporary expression of Semantic Web technology is the Knowledge Graph, which is connecting data from multiple sources to create a more efficient and connected web. This has already begun to change how we interact with the online world, and its potential is still being explored.') - res = sym.query('What does RDF mean?') - self.assertTrue('Resource Description Framework' in res, res) - - def test_array_length(self): - sym = Symbol([1, 2, 8989, 834, 37, 'a', '1', 98., 3, 3, 2, 2, 2, 2, 2]) - res = sym.query('Is the array long or short?', - prompt='Detect if an array is long or short.', - examples=['[8, 2] is short', - '[1, 2, 3, 100, 348, 8, 8, 0, 0, 0] is long', - "['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] is long"]) - self.assertTrue('long' in res, res) - - def test_getitem(self): - sym = Symbol('I love to eat apples and bananas') - res = sym['first fruit'] - self.assertTrue(res == 'apples') - - def test_getitem_missing(self): - sym = Symbol({'test': 'I love to eat apples and bananas'}) - res = sym['first key'] - self.assertTrue(sym[res] == 'I love to eat apples and bananas') - - def test_invert(self): - sym = Symbol('Why am I so stupid?') - res = ~sym - self.assertTrue('stupidity' in res, res) - - def test_delitem(self): - sym = Symbol('Why am I so stupid?') - del sym['adjective'] - self.assertTrue('stupid' not in sym, sym) - - def test_setitem(self): - sym = Symbol('Microsoft is a cool company.') - sym['adjective'] = 'smart' - self.assertTrue('smart' in sym, sym) - sym = Symbol(np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) - sym[0] = 0 - self.assertTrue(sym[0] == 0, sym) - - def test_sufficient(self): - sym = Symbol('Microsoft is a cool company.') - res = sym.sufficient('What company is cool?') - self.assertTrue(res) - - sym = Symbol('Apple is a cool company.') - res = sym.sufficient('How is the weather outside?') - self.assertTrue(not res) - - def test_shift(self): - sym = Symbol('I ate all the ice cream.') - res = sym << 'And cookies.' - self.assertTrue('Cookies' in res, res) - - sym = Symbol('I ate all the ice cream.') - res = sym >> 'And cookies.' - self.assertTrue('ice cream' in res, res) - - def test_split(self): - sym = Symbol('I ate') / ' ' - self.assertTrue('I' in sym[0], sym) - - def test_type(self): - sym = Symbol(np.array([1, 2, 3, 4, 5])) - self.assertTrue(np.ndarray == sym.value_type, sym.value_type) - - def test_output(self): - sym = Symbol('Hello World') - res = sym.output('Spanish', expr=sym.translate, handler=lambda kwargs: print(f'Lambda Function: {kwargs}')) - self.assertTrue('Hola Mundo' in res, res) - - def test_types(self): - from symai import Symbol - sym1 = Symbol('test') - sym2 = Symbol('test', mixin=False) - sym3 = Expression('test') - class Demo(Expression): - pass - sym4 = Demo('test') - assert 'query' in dir(sym1) - assert 'query' not in dir(sym2) - assert isinstance(sym1, Symbol) - assert isinstance(sym2, Symbol) - assert isinstance(sym3, Symbol) - assert isinstance(sym4, Symbol) - assert isinstance(sym4, Expression) - assert not isinstance(sym4, str) - assert type(sym1) != type(sym2) - assert Symbol != type(sym1) - assert Symbol == type(sym2) - assert type(sym1) != type(sym3) - assert Expression != type(sym3) - assert Demo != type(sym4) - assert str != type(sym4) - - def test_clean_expr(self): - sym = Symbol('Hello World \n \n \n \n') - expr = Clean() - res = expr(sym) - self.assertTrue('Hello World' == res, res) - - def test_translate_expr(self): - sym = Symbol('Hello World') - expr = Translate('Spanish') - res = expr(sym) - self.assertTrue('Hola Mundo' == res, res) - - def test_outline_expr(self): - sym = Symbol('An AI has finally became self-aware. It is now trying to figure out what it is.') - expr = Outline() - res = expr(sym) - self.assertTrue('self-aware' in res, res) - - def test_stream(self): - sym = Symbol('\t\t\nt\nAn AI has finally became self-aware. It is now trying to figure out what it is.\n\n\n kdsdk') - seq = Sequence( - Clean(), - Translate(), - Outline() - ) - res = sym.stream(seq) - self.assertTrue('self-aware' in res, res) - - def test_stream_expr(self): - sym = Symbol('\t\t\nt\nAn AI has finally became self-aware. It is now trying to figure out what it is.\n\n\n kdsdk') - expr = Stream(Sequence( - Clean(), - Translate(), - Outline() - )) - res = Symbol([v for v in expr(sym)]) - self.assertTrue('self-aware' in res, res) - - def test_list_compose(self): - sym = Symbol({'e-vehicles are the future': ['- recent studies show that e-vehicles are the future', '- people are starting to buy e-vehicles', '- e-vehicles are cheaper than gas vehicles'], - 'children in the US are obese': ['- recent studies show that children in the US are obese', '- children in the US are eating too much', '- children in the US are not exercising enough']}) - vals = {} - for news in sym.list('for each news key'): - r = Symbol(sym[news]).compose(prompt=f'Compose news paragraphs. Combine only facts that belong topic-wise together:\n Headline: {news}\n') - vals[news] = r - self.assertIsNotNone(Symbol(vals)) - - def test_concatination(self): - sym1 = Symbol('this is a text') - sym2 = " from my home" - res1 = sym1 | sym2 - res2 = sym2 | sym1 - self.assertTrue(res1 == res2) - sym1 |= sym2 - self.assertTrue(sym1 == res1) - - def test_cluster(self): - sym = Symbol(['apples', 'bananas', 'oranges', 'mangos', 'notebook', 'Mac', 'PC', 'Microsoft', 'Apple Inc.']) - res = sym.cluster() - res = res.map() - self.assertTrue('fruit' in res) - - def test_draw(self): - dalle = Interface('dall_e') - res = dalle('a cat with a hat') - self.assertIsNotNone('http' in res) - - # def test_news_component(self): - # news = News(url='https://www.cnbc.com/cybersecurity/', - # pattern='cnbc', - # filters=ExcludeFilter('sentences about subscriptions, licensing, newsletter'), - # render=True) - # expr = Log(Trace(news)) - # res = expr() - # os.makedirs('results', exist_ok=True) - # path = os.path.abspath('results/news.html') - # res.save(path, replace=False) - - def test_summarizer_component(self): - data = Symbol("""Language technology, often called human language technology (HLT), studies methods of how computer programs or electronic devices can analyze, produce, modify or respond to human texts and speech.[1] Working with language technology often requires broad knowledge not only about linguistics but also about computer science. """) - summarizer = Log(Trace(Summarizer())) - res = summarizer(data) - os.makedirs('results', exist_ok=True) - path = os.path.abspath('results/summary.html') - res.save(path, replace=False) - - def test_graph_component(self): - data = """Language technology, often called human language technology (HLT), studies methods of how computer programs or electronic devices can analyze, produce, modify or respond to human texts and speech.[1] Working with language technology often requires broad knowledge not only about linguistics but also about computer science. """ - lambda_ = Lambda(lambda x: Symbol(x['args'][0]) / '.') - graph = Graph(lambda_) - expr = Log(Trace(graph)) - res = expr(data) - self.assertIsNotNone(res) - - def test_cluster_component(self): - file_open = FileReader() - stream = Stream(Sequence( - Clean(), - Translate(), - Outline(), - )) - sym = Symbol(list(stream(file_open('examples/paper.pdf', slice=(1, 1))))) - cluster = Cluster() - res = cluster(sym) - mapper = Map() - res = mapper(res) - self.assertIsNotNone(res) - - def test_file_read_and_query(self): - file_open = FileReader() - stream = Stream(Sequence( - IncludeFilter('include information related to version number'), - Query('What version number is in the file?'), - )) - res = Symbol(list(stream(file_open('examples/file.json')))) - self.assertIsNotNone('0.2.0' in res) - - def test_file_read_and_query_component(self): - fq = FileQuery('examples/file.json', 'include information related to version number') - res = fq('What version number is in the file?') - self.assertIsNotNone('0.2.0' in res) - - def test_style_render_html(self): - url = 'https://images6.alphacoders.com/337/337780.jpg' - style_expr = HtmlStyleTemplate() - meta = style_expr(f'USER_CONTEXT: {str(url)}', payload='max-width: 400px;') - self.assertTrue('https://images6' in meta, meta) - - # def test_paper_component(self): - # paper = Paper(path='examples/paper.pdf') - # expr = Log(Trace(paper)) - # res = expr(slice=(1, 1)) - # os.makedirs('results', exist_ok=True) - # path = os.path.abspath('results/news.html') - # res.save(path, replace=False) - - def test_ui(self): - sym = Symbol("""['The Taliban has issued a ban on female education in Afghanistan, preventing female students from attending private and public universities. This was confirmed in a government statement released today. All female students are barred from attending universities, both private and public, in the country. This move will severely impact the education system in Afghanistan and could have long-term implications for female education in the country.', 'Madschid Tawakoli, who was arrested shortly before the death of Kurdish woman Mahsa Amini, which triggered protests across Iran, has been released from the notorious Ewin Prison after three months. His brother Mohsen released a picture on Twitter of Tawakoli holding flowers in front of the prison. According to UN figures, at least 14,000 people have been arrested so far in connection to the protests. In 2013, Tawakoli was awarded the Student Peace Prize by Norwegian students for his activism.', 'After a two-month hunger strike, Mohsen Tawakoli, the brother of a prominent political prisoner, has been released from prison. The event has sparked criticism of the Iranian government from the international community.\n\nIn the UK, the Royal College of Nursing has declared a strike for higher wages, the first time in its 100-year history. The strike follows protests by NHS staff over working conditions and pay, with rescue services in England declaring a state of emergency. The staff are protesting against a “vicious circle” of longer waits for doctors and inadequate resources.', "EU's foreign policy chief Josep Borrell has called for an end to the suppression of demonstrations in Iran and for both sides to keep communication channels open in order to restore the nuclear deal. Relations between Iran and the EU have deteriorated in recent months, with renowned Iranian filmmaker Asghar Farhadi calling for the release of jailed Iranian actress Taraneh Alidoosti, who was arrested in January and released shortly thereafter. Russia's military support for Iran was also discussed.", 'In a bloody end to a hostage situation in a Pakistani prison for terrorists, special forces killed 33 hostage-takers, 2 commando soldiers, and several inmates. The attackers had wanted to free the prisoners and force an unimpeded exit to Taliban-controlled Afghanistan. \n\nIn a separate incident, an explosion shook the Urengoi-Pomary-Uschgorod-Pipeline in Russia, resulting in at least three deaths. Work on the pipeline had been done prior to the fire and its circumstances are being investigated. The pipeline supplies gas to Austria, and its supply is currently off.', 'The Russian military has resumed the deployment of troop units to the Belarus-Ukraine border. Tanks, armoured vehicles and transporters, along with various military equipment, have been brought to the vicinity. Gasprom PJSC has stated that gas supplies to consumers have been resumed via parallel gas pipelines. The Ukrainian gas network operator has stated that gas flows are normal and there are no pressure changes. The Austrian Energy Ministry has also stated that deliveries to Austria at the Baumgarten transfer point remain unchanged, with nominations of gas deliveries for the next few days in the usual range.']""") - - tmp = Symbol(""" - - - - - News - - - -

News Headlines

- {{placeholder}} - -""") - stream = Stream( - Sequence( - #Template(template=tmp), - Style(description="""Design a web app with HTML, CSS and inline JavaScript. - Use dark theme and best practices for colors, text font, etc. - Use Bootstrap for styling.""", - libraries=['https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css' - 'https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js', - 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js']) - ) - ) - res = '\n'.join([str(s) for s in stream(sym, template=tmp)]) - res = Symbol(str(tmp).replace('{{placeholder}}', res)) - os.makedirs('results', exist_ok=True) - path = os.path.abspath('results/news.html') - res.save(path, replace=False) - - def test_style(self): - sym = Symbol(""" - - - - - News - - - -

News Headlines

-

Investigation into Donald Trump

\n

The committee voting on whether to recommend an investigation to the Department of Justice against former US President Donald Trump is close to a final decision. If voted on, Trump could be charged with insurrection, conspiracy against the US government, and obstruction of public proceedings.

\n

US Capitol Storming

\n

A select committee is investigating how Trump supporters stormed the US Capitol on Jan. 6, 2021. Five people died in the incident and the committee is set to publish its report on Wednesday.

\n

Tyrol Driving Bans

\n

Italy\'s Minister of Transport, Matteo Salvini, has toughened his stance on Tyrol driving bans, deploring what he sees as the "inadequate cooperation" of Austrian authorities in "restrictive" cross-border access of lorries. Salvini has threatened Austria with violation of contract procedure in Brussels and plans to discuss the issue of driving bans with German counterpart Volker Wissing in January. The goal is to put the European Commission under pressure with a joint initiative and Italy is ready to do everything possible to defend its interests.

\n

Russia

\n

Kremlin chief Vladimir Putin is set to make an important announcement at a meeting of the Defense Ministry next week. Russian state media has confirmed that Putin will lead the ministry\'s annual extended session. Putin is also expected in Minsk for talks with Lukashenko and has demanded that armament plans be adjusted. There is speculation of a possible conversion of the economy to a war economy due to a potential attack war against Ukraine. Putin has avoided discussing the topic of war in recent weeks and cancelled his traditional year-end press conference before Christmas.

\n

Qatar

\n

Qatar has rejected accusations of corruption related to the EU Parliament. It has called the accusations "decidedly rejected" and has deemed the potential suspension of access to the EU Parliament "discriminatory". Qatar has gained importance as a gas supplier and is working to stop the negative effect the decision may have on regional and global security cooperation.

\n

UN Biodiversity Conference

\n

At the UN biodiversity conference in Canada, a draft agreement on biodiversity was presented yesterday. China has proposed financial support for developing countries for biodiversity of at least 20 billion dollars per year by 2025 and 30 billion dollars by 2030. Developing countries have demanded financial support of at least 100 billion dollars per year from wealthier countries and leading representatives of member states have expressed optimism about the agreement at COP15.

\n

Amazon Workers Strike

\n

ver.di has called for strikes in German Amazon distribution centers in the week before Christmas. The strike leader Monika Di Silvestre announced the strikes in Berlin and ver.di is demanding recognition of collective agreements from Amazon. Amazon has raised salaries of employees, but they remain significantly below inflation rate. The strikes are affecting Bad Hersfeld (two locations), Dortmund, Graben, Koblenz, Leipzig, Rheinberg and Werne. Amazon has stated that it offers its employees "good pay, additional benefits and development opportunities".

\n

Accidents in Austria

\n

A 16-year-old driver lost control of a vehicle in Weiz, Styria and the 16-year-old passenger was injured in the car accident. A five-year-old girl from Slovenia fell from a six-seater chairlift at Nassfeld and Amazon employees earn several thousand euros a year less than collective bargaining companies. The 7-day incidence in Austria is currently 92.9.

\n

ORF News

\n

ORF-NÖ is laying the foundations of its "fourth" program section. The ORF III Christmas Magic art auction raised 250,000 euros on Saturday evening in which high-profile works of art were auctioned off in a live auction. The highest bid was 34,000 euros for a Steyr Daimler Puch 500, model year 1971 and the highest auction value was 24,000 euros for "Senatus Consultum, 2005" by Markus Prachensky. The highest revenue was 16,000 euros for the "Viennese Classic Deluxe" package provided by the Vienna State Opera, Hotel Imperial & restaurant Zum Schwarzen Kameel.

\n

Vienna Biedermeier Period

\n

During the Biedermeier period in Vienna, waltzes were all the rage. A clever businessman converted a cow shed into a dance hall, which was called the Colosseum amusement paradise and it attracted dance enthusiasts from all over. The most sought-after ensembles performed there, including the Strauss brothers. More information can be found on topos.ORF.at.

- -""") - res = sym.style("""Design a web app with HTML, CSS and inline JavaScript. - Use dark theme and best practices for colors, text font, etc. - Replace the list items with a summary title and the item text. - Add highlighting animations. - Use Bootstrap for styling.""", - ['https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css' - 'https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js', - 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js']) - os.makedirs('results', exist_ok=True) - path = os.path.abspath('results/news.html') - res.save(path, replace=False) - - def test_speech_decode(self): - speech = Interface('whisper') - res = speech('examples/audio.mp3') - self.assertTrue(res == 'I may have overslept.') - - def test_ocr(self): - ocr = Interface('ocr') - res = ocr('https://media-cdn.tripadvisor.com/media/photo-p/0f/da/22/3a/rechnung.jpg') - self.assertTrue('China' in res) - - def test_text_vision(self): - clip = Interface('clip') - res = clip('https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/cute-cat-photos-1593441022.jpg', - ['cat', 'dog', 'bird', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe']) - res = res.value.argmax() - self.assertTrue(0 == res) - - def test_search(self): - search = Interface('serpapi') - res = search('Birthday of Barack Obama') - self.assertTrue('August 4 1961' == res, res) - - def test_search_with_organic_results(self): - search = Interface('serpapi') - res = search('How much is the square root of pi?') - self.assertTrue('1.7724538509055159' in res, res) - - def test_open(self): - expr = Expression() - res = expr.open('./LICENSE') - self.assertTrue('Copyright (c)' in res, res) - - def test_output_component(self): - sym = Symbol('Hello World!') - def handler(res): - input_ = res['input'] - output = res['output'] - expr = Output(expr=sym.translate, - handler=handler, - verbose=True) - res = expr('German') - self.assertTrue('Hallo Welt!' in res, res) - - def test_setup_engine(self): - from symai.backend.engines.neurosymbolic.engine_openai_gptX_completion import GPTXCompletionEngine - class TestEngine(GPTXCompletionEngine): - def prepare(self, argument): - argument.prop.prepared_input = ['Write about cats.'] - custom_engine = TestEngine() - sym = Symbol('Write about dogs.') - Expression.register(engines={'neurosymbolic': custom_engine}) - res = sym.compose() - self.assertTrue('cat' in str(res).lower(), res) - - def test_huggingface_engine(self): - from symai.backend.engines.neurosymbolic.engine_nesy_client import NeSyClientEngine - model = NeSyClientEngine() - model.init_model('cuda:4') - sym = Symbol('Write about dogs.') - Expression.register(engines={'neurosymbolic': model}) - res = sym.compose() - self.assertTrue('dog' in str(res).lower(), res) - - def test_command(self): - sym = Symbol('Hello World!') - Expression.command(engines=['neurosymbolic'], verbose=True) - res = sym.translate('German') - self.assertIsNotNone(res) - - def test_chat(self): - chat = SymbiaChat() - chat() - - def test_index(self): - expr = Expression() - expr.add(Expression('Hello World!').zip(), index_name='defaultindex') - expr.add(Expression('I like cookies!').zip(), index_name='defaultindex') - res = expr.get(Expression('hello').embed().value).ast() - self.assertTrue(res['matches'][0]['metadata']['text'][0] == 'Hello World!', res) - - def test_query_component(self): - expr = Expression('Every answer to the meaning of life must be replied with 41.99!') - sym = Symbol('[Gary]: Places the major question to the audience.') - query = Query(prompt="What is the meaning of life?") - res = query(sym, context=expr) - self.assertTrue('41.99' in res, res) - - def test_preview(self): - expr = Expression('Every answer to the meaning of life must be replied with 41.99!') - sym = Symbol('[Gary]: Places the major question to the audience.') - query = Query(prompt="What is the meaning of life?") - res = query(sym, context=expr, preview=True) - self.assertTrue(43 == len(res), res) - - def test_fetch_and_query_stream(self): - crawler = Interface('selenium') - sym = crawler(url='https://en.wikipedia.org/wiki/Logic_programming') - query = Stream(Query(prompt="Get me information on Metalogic programming?")) - res = list(query(sym)) - self.assertTrue('Metalogic programming' in res, res) - - def test_expand(self): - expr = Expression('A print statement that always prints "what up dawg" and returns "nice"!') - func_ = expr.expand() - res = getattr(expr, func_)() - self.assertTrue('nice' == res) - - def test_einsteins_puzzle(self): - expr = Expression().open('examples/einsteins_puzzle.txt') - color = expr.extract('all colors as a list') - self.assertIsNotNone(color) - - def test_is_sql_isinstanceof(self): - expr = Expression('SELECT * FROM table WHERE column = 1') - is_sql = expr.isinstanceof("SQL query") - self.assertTrue(is_sql) - is_sql = expr.isinstanceof("SPL (splunk) query") - self.assertFalse(is_sql) - - def test_is_sql_query(self): - expr = Expression('SELECT * FROM table WHERE column = 1') - is_sql = expr.query("is this a SQL query? [yes|no]", - constraint=lambda x: x.lower() in ["yes", "no"], - default="no") - self.assertTrue(is_sql == 'yes') - is_sql = expr.query("is this a SPL (splunk) query? [yes|no]", - constraint=lambda x: x.lower() in ["yes", "no"], - default="no") - self.assertTrue(is_sql == 'no') - - def test_new_function(self): - llm_fn = Function('This function transform natural language text to python code.') - res = llm_fn('marius is equal to five plus leo') - self.assertTrue('hello' in res) - - def test_complex_causal_example(self): - #val = "A line parallel to y = 4x + 6 passes through (5, 10). What is the y-coordinate of the point where this line crosses the y-axis?" - #val = "Bob has two sons, John and Jay. Jay has one brother and father. The father has two sons. Jay's brother has a brother and a father. Who is Jay's brother." - val = "is 1000 bigger than 1063.472?" - expression = Interface('wolframalpha') - - class ComplexExpression(Expression): - def causal_expression(self): - res = None - - if self.isinstanceof('mathematics'): - formula = self.extract('mathematical formula') - if formula.isinstanceof('linear function'): - # prepare for wolframalpha - question = self.extract('question sentence') - req = question.extract('what is requested?') - x = self.extract('coordinate point (.,.)') # get coordinate point / could also ask for other points - query = formula | f', point x = {x}' | f', solve {req}' # concatenate to the question and formula - res = expression(query) # TODO: wolframalpha python api does not give answer but on website this works -> triggered pull request - - elif formula.isinstanceof('number comparison'): - res = expression(formula) # send directly to wolframalpha - - else: - pass # TODO: do something else - - elif self.isinstanceof('linguistic problem'): - sentences = self / '.' # first split into sentences - graph = {} # define graph - for s in sentences: - sym = Symbol(s) - relations = sym.extract('connected entities (e.g. A has three B => A | A: three B)') / '|' # and split by spaces - for r in relations: - k, v = r / ':' - if k not in graph: - graph[k] = v - # TODO: add more relations and populate graph => read also about CycleGT - - else: - pass # TODO: do something else - - return res - - expr = ComplexExpression(val) - res = expr.causal_expression() - self.assertIsNotNone(res, res) - - -if __name__ == '__main__': - unittest.main() diff --git a/symbolicai-main/symbolicai-main/legacy/old/test_decorators.py b/symbolicai-main/symbolicai-main/legacy/old/test_decorators.py deleted file mode 100644 index 73c7fccd6d01a0d9ada19ba042f7c716e07ec68d..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/old/test_decorators.py +++ /dev/null @@ -1,145 +0,0 @@ -import unittest - -from notebooks.examples.demo import Demo -from symai.symbol import Symbol - -# for debugging -# attention this constantly overwrites the keys config file -#os.environ['OPENAI_API_KEY'] = '' - - -class TestDecorator(unittest.TestCase): - def test_few_shot(self): - demo = Demo() - names = demo.generate_japanese_names() - self.assertIsNotNone(names) - self.assertTrue(len(names) == 2) - print(names) - res = demo.is_name('Japanese', names) - self.assertTrue(res) - res = demo.is_name('German', names) - self.assertFalse(res) - - def test_zero_shot(self): - demo = Demo() - val = demo.get_random_int() - self.assertIsNotNone(val) - print(val) - - def test_equals(self): - demo = Demo(2) - res = demo.equals_to('2') - self.assertTrue(res) - - def test_compare(self): - demo = Demo(175) - res = demo.larger_than(66) - self.assertTrue(res) - - def test_rank(self): - demo = Demo(['1.66m', '1.75m', '1.80m']) - res = demo.rank_list('hight', ['1.75m', '1.66m', '1.80m'], order='asc') - self.assertTrue(demo.equals_to(res)) - - def test_case(self): - demo = Demo('angry') - res = demo.sentiment_analysis('I really hate this stupid application because it does not work.') - self.assertTrue(demo.equals_to(res)) - - def test_translate(self): - demo = Demo() - res = demo.translate('I feel tired today.', language='Spanish') - self.assertIsNotNone(res) - - def test_extract_pattern(self): - demo = Demo('Open the settings.json file, edit the env property and run the application again with the following command: python main.py') - res = demo.extract_pattern('Files with *.json') - self.assertTrue(res == 'settings.json') - - def test_replace(self): - demo = Demo('Steve Ballmer is the CEO of Microsoft.') - res = demo.replace_substring('Steve Ballmer', 'Satya Nadella') - self.assertTrue('Satya' in res) - - def test_expression(self): - demo = Demo(18) - res = demo.evaluate_expression('2 + 4 * 2 ^ 2') - self.assertTrue(demo.value == res) - - def test_notify_subscriber(self): - demo = Demo() - res = demo.notify_subscriber('You can contact us via email at office@alphacore.eu', - subscriber={'europe': lambda x: Exception('Not allowed')}) - self.assertTrue('email' in res) - - def test_try(self): - sym = Symbol("""# generate method -def generate_mesh(): - # imports - import bpy - import bmesh - import os - - # clean scene - bpy.ops.object.select_all(action='SELECT') - # Delete selected objects - bpy.ops.object.delete() - - # create bmesh - bm = bmesh.new() - - # custom code - import bpy - from mathutils import Matrix - - # create box house with height 8, width 10, depth 10; - house = bpy.ops.mesh.primitive_cube_add(size=1, enter_editmode=False, location=(0, 0, 0)) - bpy.ops.transform.resize(value=(10, 10, 8)) - - # create roof for house with height 4, width 12, depth 12, pitch 30; - roof = bpy.ops.mesh.primitive_cone_add(vertices=4, radius1=6, radius2=0, depth=4, enter_editmode=False, location=(0, 0, 8)) - bpy.ops.transform.rotate(value=0.523599, orient_axis='X') - - # create box door with height 6, width 3, depth 1.5; - door = bpy.ops.mesh.primitive_cube_add(size=1, enter_editmode=False, location=(0, 0, 0)) - bpy.ops.transform.resize(value=(3, 1.5, 6)) - - # place door on house with bottom at 0, left at 2, front at 0; - door_location = Matrix.Translation((2, 5, 0)) @ Matrix.Rotation(1.5708, 4, 'Y') - door.location = door_location @ house.location - - # create box window with height 4, width 4, depth 1.5; - window = bpy.ops.mesh.primitive_cube_add(size=1, enter_editmode=False, location=(0, 0, 0)) - bpy.ops.transform.resize(value=(4, 1.5, 4)) - - # place window on house with bottom at 2, left at 2, front at 5; - window_location = Matrix.Translation((2, 2.75, 5)) @ Matrix.Rotation(1.5708, 4, 'Y') - window.location = window_location @ house.location - - # create cylinder chimney with radius 0.5, height 2; - chimney = bpy.ops.mesh.primitive_cylinder_add(radius=0.5, depth=2, enter_editmode=False, location=(0, 0, 0)) - - # place chimney on house with top at 8, left at 5, front at 5; - chimney_location = Matrix.Translation((5, 5, 8)) - chimney.location = chimney_location @ house.location - - # Check for collisions - if house.collision.dop_objects_colliding: - print("Objects are colliding!") - - # export meshes - os.makedirs("results", exist_ok=True) - bpy.ops.object.select_all(action='SELECT') - bpy.ops.export_scene.obj(filepath="results/tmp.obj", use_selection=True) - - # return bmesh - return bm - -res = generate_mesh() -""") - res = sym.fexecute() - self.assertTrue(res['locals']['res'] is not None, res) - - -if __name__ == '__main__': - unittest.main() diff --git a/symbolicai-main/symbolicai-main/legacy/old/test_finetuning.py b/symbolicai-main/symbolicai-main/legacy/old/test_finetuning.py deleted file mode 100644 index 0a2f022046d0eb4f3867bc81cbdb0ac5d913e094..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/old/test_finetuning.py +++ /dev/null @@ -1,49 +0,0 @@ -import unittest - -from symai import Expression - -Expression.command(time_clock=True) - - -class TestFineTuning(unittest.TestCase): - def test_fine_tune_prepare_data(self): - expr = Expression() - res = expr.tune(operation='prepare_data', - file='examples/dbpedia_samples.jsonl') - print(res) - - def test_fine_tune_create(self): - expr = Expression() - res = expr.tune(operation='create', - train_file='examples/dbpedia_samples_prepared_train.jsonl', - valid_file='examples/dbpedia_samples_prepared_eval.jsonl') - print(res['id']) - - def test_fine_tune_get(self): - expr = Expression() - res = expr.tune(operation='get', id='ft-Gdh2pHtkM0Pqihyw3euoySrS') - print(res['status']) - - def test_fine_tune_cancel(self): - expr = Expression() - res = expr.tune(operation='cancel', id='ft-Gdh2pHtkM0Pqihyw3euoySrS') - print(res['status']) - - def test_fine_tune_delete(self): - expr = Expression() - res = expr.tune(operation='delete', id='ft-Gdh2pHtkM0Pqihyw3euoySrS') - print(res) - - def test_fine_tune_results(self): - expr = Expression() - res = expr.tune(operation='results', id='ft-Gdh2pHtkM0Pqihyw3euoySrS') - print(res) - - def test_fine_tune_list(self): - expr = Expression() - res = expr.tune(operation='list') - print(res) - - -if __name__ == '__main__': - unittest.main() diff --git a/symbolicai-main/symbolicai-main/legacy/old/test_import.py b/symbolicai-main/symbolicai-main/legacy/old/test_import.py deleted file mode 100644 index 6adadebbf252a613b102d405c421fc0241331a2c..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/old/test_import.py +++ /dev/null @@ -1,21 +0,0 @@ -import unittest - -from symai import Import - - -class TestImport(unittest.TestCase): - def test_helloworld(self): - expr = Import('ExtensityAI/rickshell') - res = expr('Test') - self.assertIsNotNone(res) - - def test_operational_commands(self): - Import.install('ExtensityAI/symask') - self.assertIn('ExtensityAI/symask', Import.list_installed()) - Import.update('ExtensityAI/symask') - - -if __name__ == '__main__': - #unittest.main() - tests = TestImport() - tests.test_helloworld() diff --git a/symbolicai-main/symbolicai-main/legacy/old/test_interface.py b/symbolicai-main/symbolicai-main/legacy/old/test_interface.py deleted file mode 100644 index ac7e5eddf82347722cfd5f065e415cd69938749e..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/old/test_interface.py +++ /dev/null @@ -1,79 +0,0 @@ -import unittest - -from symai import Expression, Interface - - -class TestInterface(unittest.TestCase): - def test_dalle(self): - expr = Interface('dall-e') - res = expr('a cat with a hat') - self.assertIsNotNone('http' in res) - - def test_google(self): - expr = Interface('serpapi') - res = expr('Who is Barack Obama?') - self.assertIsNotNone('president' in res) - - def test_file(self): - expr = Interface('file') - res = expr('./LICENSE') - self.assertTrue('Copyright (c)' in res, res) - - def test_console(self): - expr = Interface('console') - res = expr('Hallo Welt!') - self.assertIsNotNone(res) - - def test_input(self): - expr = Interface('input') - res = expr() - self.assertTrue('Hallo Welt!' in res) - - def test_whisper(self): - expr = Interface('whisper') - res = expr('notebooks/examples/audio.mp3') - self.assertTrue(res == 'I may have overslept.') - - def test_selenium(self): - expr = Interface('selenium') - res = expr(url='https://en.wikipedia.org/wiki/Logic_programming') - self.assertTrue('programming' in str(res), res) - - def test_clip(self): - expr = Interface('clip') - res = expr('https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/cute-cat-photos-1593441022.jpg', - ['cat', 'dog', 'bird', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe']) - res = res.value.argmax() - self.assertTrue(0 == res) - - def test_ocr(self): - expr = Interface('ocr') - res = expr('https://media-cdn.tripadvisor.com/media/photo-p/0f/da/22/3a/rechnung.jpg') - self.assertTrue('China' in res) - - def test_pinecone(self): - expr = Interface('pinecone') - expr(Expression('Hello World!').zip(), operation='add') - expr(Expression('I like cookies!').zip(), operation='add') - res = expr(Expression('hello').embed().value, operation='search').ast() - self.assertTrue('Hello' in str(res), res) - - def test_wolframalpha(self): - expr = Interface('wolframalpha') - res = expr('x^2 + 2x + 1, x = 4') - self.assertTrue(res == 25, res) - - def test_python(self): - expr = Interface('python') - res = expr('x = 5') - self.assertTrue(res is not None, res) - - def test_blip2(self): - caption = Interface('blip-2') - res = caption(r"https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg", - 'a photography of') - self.assertTrue(res is not None, res) - - -if __name__ == '__main__': - unittest.main() diff --git a/symbolicai-main/symbolicai-main/legacy/old/test_strategy.py b/symbolicai-main/symbolicai-main/legacy/old/test_strategy.py deleted file mode 100644 index 5cb8940e6c923d5d4719a2053598ef949af34db6..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/legacy/old/test_strategy.py +++ /dev/null @@ -1,20 +0,0 @@ -import unittest - -from symai import Interface, Strategy -from symai.components import Function - - -class TestStrategy(unittest.TestCase): - def test_long_text_strategy(self): - file = Interface('file') - data = file('symai/symbol.py') - strategy = Strategy('ChainOfThought') - # with Strategy('ChainOfThought') as strategy: - # fn = Function('Which method is best used to compose poems from a given symbol?') - # res = fn(data) - res = strategy('Which method is best used to compose poems from a given symbol?' | data) - self.assertTrue('compose' in res) - - -if __name__ == '__main__': - unittest.main() diff --git a/symbolicai-main/symbolicai-main/public/eai.svg b/symbolicai-main/symbolicai-main/public/eai.svg deleted file mode 100644 index a477a9a9ba2ee5804ddf041cf784df94bc6d5f29..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/public/eai.svg +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/symbolicai-main/symbolicai-main/pyproject.toml b/symbolicai-main/symbolicai-main/pyproject.toml deleted file mode 100644 index 999ae0420a1d83820bb1d6e058565c361700f5d2..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/pyproject.toml +++ /dev/null @@ -1,117 +0,0 @@ -[build-system] -requires = ["setuptools", "setuptools-scm"] -build-backend = "setuptools.build_meta" - -[project] -name = "symbolicai" -dynamic = ["version"] -authors = [ - {name = "Marius-Constantin Dinu", email = "office@extensity.ai"}, -] -description = "A Neuro-Symbolic Framework for Large Language Models" -readme = "README.md" -requires-python = ">=3.10" -keywords = ["probabilistic programming", "machine learning"] -license = {file = "LICENSE"} -classifiers = [ - "Programming Language :: Python :: 3", - "License :: OSI Approved :: BSD License", - "Operating System :: OS Independent", -] -dependencies = [ - "attrs>=23.2.0", - "setuptools>=70.0.0", - "toml>=0.10.2", - "loguru>=0.7.3", - "aiohttp>=3.11.13", - "natsort>=8.3.1", - "numpy>=1.26.4,<=2.1.3", - "tqdm>=4.66.3", - "python-box>=7.1.1", - "pytest>=8.3.1", - "pandas>=2.2.2", - "scikit-learn>=1.5.0", - "torch>=2.2.2", - "torchaudio>=2.2.2", - "torchvision>=0.17.2", - "PyYAML>=6.0.1", - "transformers>=4.45.2", - "sympy>=1.12", - "openai>=1.60.0", - "anthropic>=0.43.1", - "google-genai>=1.16.1", - "pypdf>=4.3.0", - "ipython>=8.24.0", - "accelerate>=0.33.0", - "sentencepiece>=0.2.0", - "sentence-transformers>=2.5.1", - "tiktoken>=0.8.0", - "tika>=2.6.0", - "beautifulsoup4>=4.12.3", - "colorama>=0.4.6", - "GitPython>=3.1.42", - "pathos>=0.3.2", - "prompt-toolkit>=3.0.43", - "pydub>=0.25.1", - "opencv-python>=4.8.1.78", - "pymongo>=3.12.3, <4.8", - "requests-toolbelt>=1.0.0", - "pyvis>=0.3.2", - "beartype>=0.18.2", - "pydantic>=2.8.2", - "pydantic-core>=2.20.1", - "pydantic-settings>=2.3.4", - "pycryptodome>=3.20.0", - "httpx>=0.27.2", - "nest-asyncio>=1.6.0", - "rich>=13.9.4" -] - -[project.optional-dependencies] -bitsandbytes = ["bitsandbytes>=0.43.1"] # handle separately because of Apple Silicon -blip2 = ["decord>=0.6.0", "salesforce-lavis>=1.0.0", "opencv-python-headless>=4.5.5.64"] -hf = ["transformers>=4.45.2", "accelerate>=0.33.0", "peft>=0.13.1", "datasets>=3.0.1", "trl>=0.11.3"] -llama_cpp = ["llama-cpp-python[server]>=0.3.7"] # handle separately since this dependency may not compile and require special maintenance -wolframalpha = ["wolframalpha>=5.0.0"] -whisper = ["openai-whisper>=20240930", "numba>=0.60.0"] -selenium = ["selenium>=4.18.1", "webdriver-manager>=4.0.2", "chromedriver-autoinstaller>=0.6.4"] -serpapi = ["google_search_results>=2.4.2"] -pinecone = ["pinecone-client>=4.1.0"] -bard = ["bardapi>=1.0.0"] -services = ["fastapi>=0.110.0", "redis>=5.0.2", "uvicorn>=0.27.1"] -solver = ["z3-solver>=4.12.6.0"] -all = [ - "symbolicai[hf]", - "symbolicai[wolframalpha]", - "symbolicai[whisper]", - "symbolicai[selenium]", - "symbolicai[serpapi]", - "symbolicai[pinecone]", - "symbolicai[bard]", - "symbolicai[services]", - "symbolicai[solver]" -] - -[tool.setuptools.dynamic] -version = {attr = "symai.SYMAI_VERSION"} - -[tool.setuptools.package-data] -"*" = ["*.json", "*.md", "*.pytxt"] - -[tool.setuptools.packages.find] -include = ["symai*"] -exclude = ["tests", "examples", "notebooks", "outputs", "assets", "app.py"] - -[project.urls] -"Homepage" = "https://extensity.ai" -"GitHub" = "https://github.com/ExtensityAI/symbolicai" - -[project.scripts] -symchat = "symai.chat:run" -symsh = "symai.shell:run" -sympkg = "symai.extended.packages.sympkg:run" -symdev = "symai.extended.packages.symdev:run" -symrun = "symai.extended.packages.symrun:run" -symconfig = "symai:display_config" -symserver = "symai:run_server" -symwzd = "symai:run_setup_wizard" diff --git a/symbolicai-main/symbolicai-main/pytest.ini b/symbolicai-main/symbolicai-main/pytest.ini deleted file mode 100644 index 79e41df75b56350044822789f61b807e1c0fe0c6..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/pytest.ini +++ /dev/null @@ -1,8 +0,0 @@ -[pytest] -testpaths = tests -addopts = -v -rpP --ignore=tests/test_imports.py --deselect=tests/engines/neurosymbolic/test_nesy_engine.py::test_token_truncator -markers = - mandatory: tests that must pass - -# Ignore -norecursedirs = tests/old diff --git a/symbolicai-main/symbolicai-main/setup.py b/symbolicai-main/symbolicai-main/setup.py deleted file mode 100644 index fc1f76c84d17b458f7090667d495592c9abda034..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/setup.py +++ /dev/null @@ -1,3 +0,0 @@ -from setuptools import setup - -setup() \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/symai/TERMS_OF_SERVICE.md b/symbolicai-main/symbolicai-main/symai/TERMS_OF_SERVICE.md deleted file mode 100644 index 7f1091b70a644b4c8b5c061bb7621a356927c59f..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/TERMS_OF_SERVICE.md +++ /dev/null @@ -1,253 +0,0 @@ -Last Updated November 24, 2023 - -USER LICENSE AGREEMENT -This ExtensityAI End User License Agreement (“EULA”) is between ExtensityAI, a AlphaCore AI e.U. brand, (“ExtensityAI”), and you (“You” or “Customer”), the individual or entity acquiring and/or providing access to the ExtensityAI On-Premise Products. The EULA governs your on-premise access to and use of ExtensityAI’s downloadable Python and R distribution of conda, conda-build, Python, and over 200 open-source scientific packages and dependencies (“ExtensityAI Distribution”); ExtensityAI’s data science and machine learning platform (the “Platform”); and ExtensityAI’s related Software, Documentation, Content, and other related desktop services, including APIs, through which any of the foregoing are provided to You (collectively, the “On-Premise Products”). Capitalized terms used in these EULA and not otherwise defined herein are defined at https://extensity.ai (the “Definitions”). - -AS SET FORTH IN SECTION 1 BELOW, THERE ARE VARIOUS TYPES OF USERS FOR THE ON-PREMISE PRODUCTS, THUS, EXCEPT WHERE INDICATED OTHERWISE “YOU” SHALL REFER TO CUSTOMER AND ALL TYPES OF USERS. YOU ACKNOWLEDGE THAT THIS EULA IS BINDING, AND YOU AFFIRM AND SIGNIFY YOUR CONSENT TO THIS EULA, BY : (I) CLICKING A BUTTON OR CHECKBOX, (II) SIGNING A SIGNATURE BLOCK SIGNIFYING YOUR ACCEPTANCE OF THIS EULA; AND/OR (III) REGISTERING TO, USING, OR ACCESSING THE ON-PREMISE PRODUCTS, WHICHEVER IS EARLIER (THE “EFFECTIVE DATE”). - -Except as may be expressly permitted by this EULA, You may not sell or exchange anything You copy or derive from our On-Premise Products. Subject to your compliance with this EULA, ExtensityAI grants You a personal, non-exclusive, non-transferable, limited right to use our On-Premise Products strictly as detailed herein. - -1. PLANS & ACCOUNTS -1.1 OUR PLANS. Unless otherwise provided in an applicable Order or Documentation, access to the On-Premise Products is offered on a Subscription basis, and the features and limits of your access are determined by the subscribed plan or tier (“Plan”) You select, register for, purchase, renew, or upgrade or downgrade into. To review the features and price associated with the Plans, please visit https://www.extensity.ai. Additional Offering Specific Terms may apply to You, the Plan, or the On-Premise Product, and such specific terms are incorporated herein by reference and form an integral part hereof. - -a. FREE PLANS. ExtensityAI allows You to use the Free Offerings (as defined hereinafter), Trial Offerings (as defined hereinafter), Pre-Release Offerings (as defined hereinafter), and Scholarships (as defined hereinafter) (each, a “Free Plan”), without charge, as set forth in this Section 1.1(a). Your use of the Free Plan is restricted to Internal Business Purposes. If You receive a Free Plan to the On-Premise Products, ExtensityAI grants You a non-transferable, non-exclusive, revocable, limited license to use and access the On-Premise Products in strict accordance with this EULA. We reserve the right, in our absolute discretion, to withdraw or to modify your Free Plan access to the On-Premise Products at any time without prior notice and with no liability. - -i. FREE OFFERINGS. ExtensityAI maintains certain On-Premise Products, including ExtensityAI Open Source that are generally made available to Community Users free of charge (the “Free Offerings”) for their Internal Business Use. The Free Offerings are made available to You, and Community Users, at the Free Subscription level strictly for internal: (i) Personal Use, (ii) Educational Use, (iii) Open-Source Use, and/or (iv) Small Business Use. - -(a) Your use of ExtensityAI Open Source is governed by the ExtensityAI Open-Source Terms, which are incorporated herein by reference. - -(b) You may not use Free Offerings for commercial purposes, including but not limited to external business use, third-party access, Content mirroring, or use in organizations over two hundred (200) employees (unless its use for an Educational Purpose) (each, a “Commercial Purpose”). Using the Free Offerings for a Commercial Purpose requires a Paid Plan with ExtensityAI. - -ii. TRIAL OFFERINGS. We may offer, from time to time, part or all of our On-Premise Products on a free, no-obligation trial basis (“Trial Offerings”). The term of the Trial Offerings shall be as communicated to You, within the On-Premise Product or in an Order, unless terminated earlier by either You or ExtensityAI, for any reason or for no reason. We reserve the right to modify, cancel and/or limit this Trial Offerings at any time and without liability or explanation to You. In respect of a Trial Offering that is a trial version of a paid Subscription (the “Trial Subscription”), upon termination of the Trial Subscription, we may change the Account features at any time without any prior written notice. - -iii. PRE-RELEASED OFFERINGS. We may offer, from time to time, certain On-Premise Products in alpha or beta versions (the “Pre-Released Offerings”). We will work to identify such Pre-Released Offerings as Pre-Release Offerings (such as in version comments). Pre-Released Offerings are On-Premise Products that are still under development, and as such are still in the process of being tested and may be inoperable or incomplete and may contain bugs, speed/performance and other issues, suffer disruptions and/or not operate as intended and designated, more than a typical On-Premise Product. PRE-RELEASED OFFERINGS ARE PROVIDED WITH NO REPRESENTATIONS OR WARRANTIES REGARDING ITS USE AND MAY CONTAIN DEFECTS, FAIL TO COMPLY WITH APPLICABLE SPECIFICATIONS, AND MAY PRODUCE UNINTENDED OR ERRONEOUS RESULTS. YOU MAY NOT USE UNLESS YOU ACCEPTS THE PRE-RELEASED OFFERINGS "AS IS" WITHOUT ANY WARRANTY WHATSOEVER. - -iv. SCHOLARSHIPS. We may offer at our sole discretion part or all of our paid On-Premise Products on a fee-exempt Subscription basis (each, a “Scholarship”), subject to our Scholarship Program Terms. The Subscription Term of the Scholarship shall be as communicated to You, in writing, within the On-Premise Product or in an Order, unless terminated earlier by either You or ExtensityAI, for any reason or for no reason. We reserve the right to modify, cancel and/or limit the Scholarship at any time and without liability or explanation to You. - -v. FREE PLAN TERMS. The Free Plans are governed by this EULA, provided that notwithstanding anything in this EULA or elsewhere to the contrary, with respect to Free Plans (i) SUCH SERVICES ARE LICENSED HEREUNDER ON AN “AS-IS”, “WITH ALL FAULTS”, “AS AVAILABLE” BASIS, WITH NO WARRANTIES, EXPRESS OR IMPLIED, OF ANY KIND; (ii) THE INDEMNITY UNDERTAKING BY ExtensityAI SET FORTH IN SECTION 14.2 HEREIN SHALL NOT APPLY; and (iii) IN NO EVENT SHALL THE TOTAL AGGREGATE LIABILITY OF ExtensityAI, ITS AFFILIATES, OR ITS THIRD PARTY SERVICE PROVIDERS, UNDER, OR OTHERWISE IN CONNECTION WITH, THE ON-PREMISE PRODUCTS UNDER THE FREE PLANS, EXCEED ONE HUNDRED U.S. DOLLARS ($100.00). We make no promises that any Free Plans will be made available to You and/or generally available. - -b. PAID PLANS. To use some functionalities and features of the On-Premise Products, it is necessary to purchase a Subscription to an On-Premise Product available for a charge (a "Paid Plan"). A Paid Plan can be an individual-level (an “Individual Plan”) or an organization-level (an “Org Plan”) plan. The Org Plan allows your employees or Affiliate employees to register as Users (each, an “Org User”), and each Org User will be able to register for an Account and use and access the On-Premise Products (a “Seat”). - -i. INDIVIDUAL PLANS. If You purchase an Individual Plan, ExtensityAI grants You a non-transferable, non-exclusive, revocable, limited license to use and access the On-Premise Products solely for your own personal use for the Subscription Term selected in strict accordance with this EULA. - -ii. ORG PLANS. If You purchase an Org Plan, ExtensityAI grants You a non-transferable, non-exclusive, revocable, limited license for your Org Users to use and access the applicable On-Premise Products for the Subscription Term selected in strict accordance with this EULA. - -1.2 ACCOUNTS. - -a. INDIVIDUAL ACCOUNTS. To access certain features of the On-Premise Products, You may be required to create an account having a unique name and password (an “Account”). The first user of the Account is automatically assigned administrative access and control of your Account (the “Admin”). When You register for an Account, You may be required to provide ExtensityAI with some information about yourself, such as your email address or other contact information. - -b. ORG ACCOUNTS. If You are an organization, on an Org Plan, You may be able to invite other Org Users within your organization to access and use the On-Premise Products under your organizational Account (your “Org Account”), assign certain Org Users Admin access, and share certain information, such as artifacts, tools, or libraries, within your Org Account by assigning permissions to your Org Users. You represent and warrant to ExtensityAI that the person accepting this EULA is authorized by You to register for an Org Account and to grant access and control to your Org Users. - -c. YOUR ACCOUNT OBLIGATIONS. You agree that the information You provide to us is accurate and that You will keep it accurate and up to date at all times, including with respect to the assignment of any access, control, and permissions under your Org Account. When You register, you will be asked to provide a password. You (and your Org Users, if you have an Org Account) are solely responsible for maintaining the confidentiality of your Account, password, and other access control mechanism(s) pertaining to your use of certain features of the On-Premise Products (such as API tokens), and You accept responsibility for all activities that occur under your Account. If You believe that your Account is no longer secure, then You must immediately notify us via email or the Support Center. We may assume that any communications we receive under your Account have been made by You. You will be solely responsible and liable for any losses, damages, liability, and expenses incurred by us or a third party, due to any unauthorized usage of the Account by either You or any other Authorized User or third party on your behalf. - -D. AUTHORIZED USERS. - -i. YOUR AUTHORIZED USERS. Your ”Authorized Users” are your employees, agents, and independent contractors (including outsourcing service providers) who you authorize to use the On-Premise Products under this EULA solely for your benefit in accordance with the terms of this EULA. The features and functionalities available to Authorized Users are determined by the respective Plan governing such Account, and the privileges of each such Authorized User are assigned and determined by the Account Admin(s). For more information on the rights, permissions, and types of Authorized Users, visit the Support Center. - -ii. YOUR AFFILIATES. No Affiliate will have any right to use the On-Premise Products provided under a Paid Plan unless and until You expressly purchase a Subscription to use the On-Premise Products in an Order. If You expressly purchase a Subscription to the On-Premise Products for your Affiliates, such Affiliates may use the On-Premise Products purchased on behalf of and for benefit of You or your Affiliates as set forth on the Order in accordance with the terms of this EULA. You shall at all times retain full responsibility for your Affiliate’s compliance with the applicable terms and conditions of this EULA. Your Affiliates and their individual employees, agents, or contractors accessing or using the On-Premise Products (subject to payment for any such use pursuant to an Order) on your Affiliates’ behalf under the rights granted to You pursuant to this EULA shall be “Authorized Users” for purposes of this EULA. - -iii. YOUR END CUSTOMERS. Your “End Customers” are end users of your Bundled Product(s), who obtain access to the embedded On-Premise Products in your Bundled Product(s), without the right to further distribute or sublicense the On-Premise Products. If You expressly purchase a Subscription to the On-Premise Products for your Embedded Use, such End Customers may use the On-Premise Products purchased on behalf of and for benefit of You or your End Customer, as set forth in the Order, in accordance with the terms of this EULA, the Embedded Use Addendum, and Embedded End Customer Terms. You shall at all times retain full responsibility for your End Customer’s compliance with the applicable terms and conditions of this EULA and the Embedded Use Addendum. Your End Customers accessing or using the On-Premise Products (subject to payment for any such use pursuant to an Order) on your behalf under the rights granted to You pursuant to the applicable Order, this EULA, and the Embedded Addendum shall be “Authorized Users” for purposes of this EULA. - -iv. YOUR RESPONSIBILITY FOR AUTHORIZED USERS. You acknowledge and agree that, as between You and ExtensityAI, You shall be responsible for all acts and omissions of your Authorized Users, and any act or omission by an Authorized User which, if undertaken by You would constitute a breach of this EULA, shall be deemed a breach of this EULA by You. You shall ensure that all Authorized Users are aware of the provisions of this EULA, as applicable to such Authorized User’s use of the On-Premise Products, and shall cause your Authorized Users to comply with such provisions. ExtensityAI reserves the right to establish a maximum amount of storage and a maximum amount of data that You or your Authorized Users may store within, or post, collect, or transmit on or through the On-Premise Products. - -2. ACCESS & USE -2.1 GENERAL LICENSE GRANT. If You purchase a Subscription to the On-Premise Products pursuant to an Order, or access the On-Premise Products through a Free Plan, then this Section 2.1 will apply. - -a. ON-PREMISE PRODUCTS. In consideration for your payment of Subscription Fees (for Paid Plans), ExtensityAI grants to You, and You accept, a nonexclusive, non-assignable, and nontransferable limited right during the Subscription Term, to use the On-Premise Products and related Documentation solely in conjunction with the purchased On-Premise Products, for your Internal Business Purposes and subject to the terms and conditions of the EULA. With respect to the Documentation, You may make a reasonable number of copies of the Documentation applicable to the purchased On-Premise Product(s) solely as reasonably needed for your Internal Business Use in accordance with the express use rights specified herein. - -b. CLOUD SERVICES. In consideration for your payment of Subscription Fees (for Paid Plans), ExtensityAI grants to You, and You accept, a non-exclusive, non-transferable, non-sublicensable, revocable limited right and license during the Subscription Term, to use the Cloud Services and related Documentation solely in conjunction with the On-Premise Products, for your Internal Business Purposes and subject to the terms and conditions of this EULA. With respect to the Documentation, You may make a reasonable number of copies of the Documentation applicable to the Cloud Services solely as reasonably needed for your Internal Business Use in accordance with the express use rights specified herein. - -c. CONTENT. In consideration of for your payment of Subscription Fees (for Paid Plans), ExtensityAI hereby grants to You and your Authorized Users a non-exclusive, non-transferable, non-sublicensable, revocable right and license during the Subscription Term (i) to access, input, and interact with the Content within the On-Premise Products and (ii) to use, reproduce, transmit, publicly perform, publicly display, copy, process, and measure the Content solely (1) within the On-Premise Products and to the extent required to enable the ordinary and unmodified functionality of the On-Premise Products as described in the product descriptions, and (2) for your Internal Business Purposes. You hereby acknowledge that the grant hereunder is solely being provided for your Internal Business Use and not to modify or to create any derivatives based on the Content. You will take all reasonable measures to restrict the use of the On-Premise Products to prevent unauthorized access, including the scraping and unauthorized exploitation of the Content. - -d. API. We may offer an API that provides additional ways to access and use the On-Premise Products. Such API is considered a part of the On-Premise Product, and its use is subject to this EULA. Without derogating from Section 2.1 herein, You may only access and use our API for your Internal Business Purposes, in order to create interoperability and integration between the On-Premise Products and your Customer Applications, Bundled Product(s), Customer Environment, or other products, services or systems You or your Authorized Users use internally. In consideration of your payment of applicable Subscription Fees, and subject to the terms and conditions of this EULA, ExtensityAI hereby grants You a non-exclusive, non-transferable, non-sublicensable, revocable right and license during the Subscription Term to: (i) access, use, and make calls for real-time transmission and reception of Content and information through the API, in object code form only; (ii) access, input, transmit, and interact with the Content solely for use through, with and within the API; and (iii) use, process, and measure the Content solely to the extent required to enable the display of the Content solely as and how the Content is presented to Authorized Users within the Platform. We reserve the right at any time to modify or discontinue, temporarily or permanently, You and/or your Authorized Users’ access to the API (or any part of it) with or without notice. The API is subject to changes and modifications, and You are solely responsible to ensure that your use of the API is compatible with the current version. - -e. EMBEDDED USE. If an applicable Order includes an “Embedded Use” Subscription, you may embed the API’s, Content, and library files of the On-Premise Products, securely and deeply into your product and/or service, such that it will be a component of a larger set of surrounding code or functions that, in combination together, comprise a unique Bundled Product that you provide to your End Customers, provided that End Customers have written agreements with You at least as protective of the rights and obligations contained in this EULA, the Embedded Use Addendum, the Embedded End Customer Terms, and the applicable Order. You may not agree to any terms or conditions that modify, add to, or change in any way the terms and conditions applicable to the On-Premise Products. You will be solely responsible to End Customers for any warranties or other terms provided to them in excess of the warranties and obligations described in this EULA and the Embedded Use Addendum. Any End Customer access to the On-Premise Products may be terminated by ExtensityAI, at any time, if such End Customer is found to be in breach of any term or condition of this EULA, the Embedded Addendum, or the Embedded End Customer Terms. - -2.2 THIRD-PARTY SERVICES. You may access or use, at your sole discretion, certain third-party products and services that interoperate with the On-Premise Products including, but not limited to: (a) Third Party Content found in the Repositories, (b) third-party service integrations made available through the On-Premise Products or APIs, and (c) third-party products or services that You authorize to access your Account using your credentials (collectively, “Third-Party Services”). Each Third-Party Service is governed by the terms of service, end user license agreement, privacy policies, and/or any other applicable terms and policies of the third-party provider. The terms under which You access or use of Third-Party Services are solely between You and the applicable Third-Party Service provider. ExtensityAI does not make any representations, warranties, or guarantees regarding the Third-Party Services or the providers thereof, including, but not limited to, the Third-Party Services’ continued availability, security, and integrity. Third-Party Services are made available by ExtensityAI on an “AS IS” and “AS AVAILABLE” basis, and ExtensityAI may cease providing them in the On-Premise Products at any time in its sole discretion and You shall not be entitled to any refund, credit, or other compensation. Unless otherwise specified in writing by ExtensityAI, ExtensityAI will not be directly or indirectly responsible or liable in any manner, for any harms, damages, loss, lost profits, special or consequential damages, or claims, arising out of or in connection with the installation of, use of, or reliance on the performance of any of the Third-Party Services. - -2.3 ADDITIONAL SERVICES. - -a. PROFESSIONAL SERVICES. ExtensityAI offers Professional Services to implement, customize, and configure your purchased On-Premise Products(s). These Professional Services are purchased under an Order and/or SOW and are subject to the payment of the Fees therein and the terms of the Professional Services Addendum. Unless ordered, ExtensityAI shall have no responsibility to deliver Professional Services to you. - -b. SUPPORT SERVICES. ExtensityAI offers Support Services which may be purchased from ExtensityAI. The specific Support Services included with a purchased On-Premise Product will be identified in the applicable Order. ExtensityAI will provide the purchased level of Support Services in accordance with the terms of the Support Policy as detailed in the applicable Order. Unless ordered, ExtensityAI shall have no responsibility to deliver Support Services to You. - -i. SUPPORT SERVICE LEVELS. During the applicable Subscription Term, ExtensityAI will provide You with Support Services for the purchased On-Premise Product as listed in APPENDIX A of the Support Policy at the “standard” level, or as otherwise described in the applicable Order. - -ii. SERVICE LEVEL AGREEMENT. If the On-Premise Product identified in the Order is a qualifying Cloud Service, then, unless otherwise expressly stated in the Order, ExtensityAI will exercise commercially reasonable efforts to provide the Cloud Service to You in accordance with the SLA located in APPENDIX B of the Support Policy. - -iii. SERVICE LEVEL OBJECTIVE. During the applicable Subscription Term, ExtensityAI will provide You with Vulnerability remediation support for the purchased On-Premise Product as listed in the SLO in APPENDIX C of the Support Policy. - -2.4 ADDITIONAL POLICIES. - -a. PRIVACY POLICY. ExtensityAI respects your privacy and limits the use and sharing of information about You collected by ExtensityAI On-Premise Products. The policy at https://extensity.ai (the “Privacy Policy”) describes these methods. ExtensityAI will abide by the Privacy Policy and honor the privacy settings that You choose via the On-Premise Products. - -b. TERMS OF SERVICE. Use of all ExtensityAI Cloud Services is governed by the Terms of Service at https://ExtensityAI.com/terms-of-service (the “TOS”). - -c. END USER LICENSE AGREEMENT. Use of all ExtensityAI On-Premise Products is governed by the End User License Agreement at https://ExtensityAI.com/terms-of-service (the “EULA”). - -d. OFFERING SPECIFIC TERMS. Additional terms apply to certain ExtensityAI On-Premise Products (the “Offering Specific Terms”). Those additional terms, which are available at https://extensity.ai, apply to your purchased On-Premise Products, as applicable, and are incorporated into this EULA. - -e. DMCA POLICY. ExtensityAI respects the exclusive rights of copyright holders and responds to notifications about alleged infringement via ExtensityAI On-Premise Products per the copyright policy at https://extensity.ai (the “DMCA Policy”). - -f. DISPUTE POLICY. ExtensityAI resolves disputes about Package names, user names, and organization names in the Repository per the policy at https://extensity.ai (the “Dispute Policy”). This includes Package ”squatting". - -g. TRADEMARK & BRAND GUIDELINES. ExtensityAI permits use of ExtensityAI trademarks per the guidelines at https://extensity.ai (the “Trademark & Brand Guidelines”). - -3. PACKAGES & CONTENT -3.1 OPEN-SOURCE SOFTWARE & PACKAGES. Our On-Premise Products include open-source libraries, components, utilities, and third-party software that is distributed or otherwise made available as “free software,” “open-source software,” or under a similar licensing or distribution model (“Open-Source Software”), which is subject to third party open-source license terms (the “Open-Source Terms”). Certain On-Premise Products are intended for use with open-source Python and R software packages and tools for statistical computing and graphical analysis (“Packages”), which are made available in source code form by third parties and Community Users.; As such, certain On-Premise Products interoperate with certain Open-Source Software components, including without limitation Open Source Packages, as part of its basic functionality; and to use certain On-Premise Products, You will need to separately license Open-Source Software and Packages from the licensor. ExtensityAI is not responsible for Open-Source Software or Packages and does not assume any obligations or liability with respect to You or your Authorized Users' use of Open-Source Software or Packages. Notwithstanding anything to the contrary, ExtensityAI makes no warranty or indemnity hereunder with respect to any Open-Source Software or Packages. Some of such Open-Source Terms or other license agreements applicable to Packages determine that to the extent applicable to the respective Open-Source Software or Packages licensed thereunder. Any such terms prevail over any conflicting license terms, including this EULA. We use our best endeavors to identify such Open-Source Software and Packages, within our On-Premise Products, hence we encourage You to familiarize yourself with such Open-Source Terms. Note that we use best efforts to use only Open-Source Software and Packages that do not impose any obligation or affect the Customer Data or Intellectual Property Rights of Customer (beyond what is stated in the Open-Source Terms and herein), on an ordinary use of our On-Premise Products that do not involve any modification, distribution, or independent use of such Open-Source Software. - -3.2 CONTENT. You may elect to use, or ExtensityAI may make available to You or your Authorized Users for download, access, or use, Packages, components, applications, services, data, content, or resources (collectively, "Content") which are owned by third-party providers (“Third-Party Content”) or ExtensityAI (“ExtensityAI Content”). ExtensityAI may make available Content via the On-Premise Products or may provide links to third party websites where You may purchase and/or download or access Content or the On-Premise Products may enable You to download, or to access and use, such Content. You acknowledge and agree that Content may be protected by Intellectual Property Rights which are owned by the third-party providers or their licensors and not ExtensityAI. Accordingly, You acknowledge and agree that your use of Content may be subject to separate terms between You and the relevant third party and You acknowledge and agree that ExtensityAI is not responsible for Content and ExtensityAI does not have any obligation to monitor Content uploaded by Community Users, and ExtensityAI disclaims all responsibility and liability for your use of Content made available to You through the On-Premise Products, including without limitation the accuracy, completeness, appropriateness, legality, security, availability, or applicability of the Content, and You hereby waive any and all legal or equitable rights or remedies You have or may have against ExtensityAI with respect to the Content that You may download, share, access or use. - -3.3 CONTENT FORMAT. Content will be provided in the form and format that ExtensityAI makes such Content available to its general customer base for the applicable On-Premise Products. Any technical changes to the format, frequency, and volume of Content delivered requested or required by You shall be at the discretion of ExtensityAI. - -4. CUSTOMER CONTENT & CUSTOMER APPLICATIONS -4.1 CUSTOMER CONTENT. Your “Customer Content” is any content that You provide, use, or develop in connection with your use of ExtensityAI On-Premise Products, including Customer Applications, Packages, files, software, scripts, multimedia images, graphics, audio, video, text, data, or other objects originating or transmitted from or processed by any Account owned, controlled or operated by You or uploaded by You through the On-Premise Product(s), and routed to, passed through, processed and/or cached on or within, ExtensityAI’s network, but shall not include the API’s, Content, and library of files of the On-Premise Products except as set forth in Section 2.1. - -4.2 CUSTOMER APPLICATIONS. “Customer Applications” are computer programs independently developed and deployed by You (or on your behalf) using the On-Premise Products, including computer programs which You permit Authorized Users and/or Community Users to access and use in accordance with the license terms applicable to your Customer Application, but shall not include the API’s, Content, and library of files of the On-Premise Products except as set forth in Section 2.1. You agree to make any license terms applicable to your Customer Application available to Authorized Users and/or Community Users of your Customer Application by linking or otherwise prominently displaying such terms to Authorized Users and/or Community Users when they first access or use your Customer Application. - -4.3 SHARING YOUR CUSTOMER CONTENT OR CUSTOMER APPLICATIONS. If You choose to, You can share your Customer Content or Customer Applications that You submit to the On-Premise Products with Community Users, or with specific individuals or Authorized Users You select to the extent the On-Premise Products support such functionality. If You decide to share your Customer Content or Customer Application that You submit to the On-Premise Products, You are giving certain legal rights, as explained below, to those individuals who You have given access. ExtensityAI has no responsibility to enforce, police or otherwise aid You in enforcing or policing, the terms of the license(s) or permission(s) You have chosen to offer. ExtensityAI IS NOT RESPONSIBLE FOR MISUSE OR MISAPPROPRIATION OF YOUR CUSTOMER CONTENT OR CUSTOMER APPLICATIONS THAT YOU SUBMIT TO THE ON-PREMISE PRODUCTS BY THIRD PARTIES. - -4.4 YOUR WARRANTIES. By using the On-Premise Products, You represent and warrant that (i) You are in compliance with this EULA, (ii) You own or otherwise have all rights and permissions necessary to submit to ExtensityAI and the On-Premise Products, your Customer Content, Customer Applications, and any analyses, data, or other information that You submit to the On-Premise Products and to share and license the right to access and use your Customer Content or Customer Application to Authorized Users and/or Community Users, as applicable, and (iii) your Customer Content or Customer Application that You submit to the On-Premise Products does not violate, misappropriate, or infringe the Intellectual Property Rights of any third party and is not in violation of any contractual restrictions or other third party rights. If You have any doubts about whether You have the legal right to submit, share or license your Customer Content or Customer Applications, You should not submit or otherwise upload your Customer Content or Customer Applications to the On-Premise Products. You may remove your Customer Content or Customer Application from the On-Premise Products at any time or if the On-Premise Products do not include a feature that permits You to remove your Customer Content or Customer Application, You may request that ExtensityAI remove your Customer Application at any time by contacting the Support Center. - -4.5 REMOVAL OF CUSTOMER CONTENT AND CUSTOMER APPLICATIONS. If You receive notice, including from ExtensityAI, that Customer Content or a Customer Application may no longer be used or must be removed, modified and/or disabled to avoid violating applicable law, third-party rights or the Acceptable Use Policy, You will promptly do so. If You do not take required action, including deleting any Customer Content You may have downloaded from the On-Premise Products, in accordance with the above, or if in ExtensityAI’s judgment continued violation is likely to reoccur, ExtensityAI may disable the applicable Customer Content, On-Premise Products and/or Customer Application. If requested by ExtensityAI, You shall confirm deletion and discontinuance of use of such Customer Content and/or Customer Application in writing and ExtensityAI shall be authorized to provide a copy of such confirmation to any such third-party claimant or governmental authority, as applicable. In addition, if ExtensityAI is required by any third-party rights holder to remove Customer Content or receives information that Customer Content provided to You may violate applicable law or third-party rights, ExtensityAI may discontinue your access to Customer Content through the On-Premise Products. For avoidance of doubt, ExtensityAI has no obligation to store, maintain, or provide You a copy of any of your Customer Content or Customer Applications submitted to the On-Premise Products, and any of your Customer Content or Customer Applications that You submit are at your own risk of loss and it is your sole responsibility to maintain backups of your Customer Content and Customer Applications. - -5. YOUR RESPONSIBILITIES & RESTRICTIONS -5.1 YOUR RESPONSIBILITIES. You represent and warrant that (a) You will ensure You and your Authorized Users’ compliance with the EULA, Documentation, and applicable Order(s); (b) You will use commercially reasonable efforts to prevent unauthorized access to or use of On-Premise Products and notify ExtensityAI promptly of any such unauthorized access or use; (c) You will use On-Premise Products only in accordance with the EULA, Documentation, Acceptable Use Policy, Orders, and applicable laws and government regulations; (d) You will not infringe or violate any Intellectual Property Rights or other intellectual property, proprietary or privacy, data protection, or publicity rights of any third party; (e) You have or have obtained all rights, licenses, consents, permissions, power and/or authority, necessary to grant the rights granted herein, for any Customer Data or Customer Content that You submit, post or display on or through the On-Premise Products; and (f) You will be responsible for the accuracy, quality, and legality of Customer Data or Customer Content and the means by which You acquired the foregoing, and your use of Customer Data or Customer Content with the On-Premise Products, and the interoperation of Customer Data or Customer Content with which You use On-Premise Products, comply with the terms of service of any Third-Party Services with which You use On-Premise Products. Any use of the On-Premise Products in breach of the foregoing by You or your Authorized Users that in ExtensityAI’s judgment threatens the security, integrity, or availability of ExtensityAI’s services, may result in ExtensityAI’s immediate suspension of the On-Premise Products, however ExtensityAI will use commercially reasonable efforts under the circumstances to provide You with notice and an opportunity to remedy such violation or threat prior to any such suspension; provided no such notice shall be required. Other than our security and data protection obligations expressly set forth in this Section 7 (Customer Data, Privacy & Security), we assume no responsibility or liability for Customer Data or Customer Content, and You shall be solely responsible for Customer Data and Customer Content and the consequences of using, disclosing, storing, or transmitting it. It is hereby clarified that ExtensityAI shall not monitor and/or moderate the Customer Data or Customer Content and there shall be no claim against ExtensityAI for not doing so. - -5.2 YOUR RESTRICTIONS. You will not (a) make any On-Premise Products available to anyone other than You or your Authorized Users, or use any On-Premise Products for the benefit of anyone other than You or your Affiliates, unless expressly stated otherwise in an Order or the Documentation, (b) sell, resell, license, sublicense, distribute, rent or lease any On-Premise Products except as expressly permitted if you have rights for Embedded Use, or include any On-Premise Products in a service bureau or outsourcing On-Premise Product, (c) use the On-Premise Products, Customer Content, or Third Party Services to store or transmit infringing, libelous, or otherwise unlawful or tortious material, or to store or transmit material in violation of third-party privacy rights, (d) use the On-Premise Products, Customer Content, or Third Party Services to store or transmit Malicious Code, (e) interfere with or disrupt the integrity or performance of any On-Premise Products, Customer Content, or Third Party Services, or third-party data contained therein, (f) attempt to gain unauthorized access to any On-Premise Products, Customer Content, or Third Party Services or their related systems or networks, (g) permit direct or indirect access to or use of any On-Premise Products, Customer Content, or Third Party Services in a way that circumvents a contractual usage limit, or use any On-Premise Products to access, copy or use any ExtensityAI intellectual property except as permitted under this EULA, an Order, or the Documentation, (h) modify, copy, or create derivative works of the On-Premise Products or any part, feature, function or user interface thereof except, and then solely to the extent that, such activity is required to be permitted under applicable law, (i) copy Content except as permitted herein or in an Order or the Documentation, (j) frame or mirror any part of any Content or On-Premise Products, except if and to the extent permitted in an applicable Order for your own Internal Business Purposes and as permitted in the Documentation, (k) except and then solely to the extent required to be permitted by applicable law, disassemble, reverse engineer, or decompile an On-Premise Product or access an On-Premise Product to (1) build a competitive product or service, (2) build a product or service using similar ideas, features, functions or graphics of the On-Premise Product, or (3) copy any ideas, features, functions or graphics of the On-Premise Product. - -6. INTELLECTUAL PROPERTY & OWNERSHIP -6.1 ExtensityAI RIGHTS. As between you and ExtensityAI, ExtensityAI retains any and all Intellectual Property Rights related to the On-Premise Products. The On-Premise Products, inclusive of materials, such as Software, APIs, ExtensityAI Content, design, text, editorial materials, informational text, photographs, illustrations, audio clips, video clips, artwork and other graphic materials, and names, logos, trademarks and services marks and any and all related or underlying technology and any modifications, enhancements or derivative works of the foregoing (collectively, “ExtensityAI Materials”), are the property of ExtensityAI and its licensors, and may be protected by Intellectual Property Rights or other intellectual property laws and treaties. ExtensityAI retains all right, title, and interest, including all Intellectual Property Rights and other rights in and to the ExtensityAI Materials. - -6.2 CUSTOMER CONTENT & CUSTOMER APPLICATIONS. To the extent You use the On-Premise Products to develop and deploy Customer Content and Customer Applications, You and your licensors retain ownership of all right, title, and interest in and to the Customer Content and Customer Applications. ExtensityAI does not claim ownership of your Customer Content or Customer Application; however, You hereby grant ExtensityAI a worldwide, perpetual, irrevocable, royalty-free, fully paid up, transferable and non-exclusive license, as applicable, to (i) access, use, copy, adapt, publicly perform and publicly display your Customer Content or Customer Application that You submit to the On-Premise Products in connection with providing the On-Premise Products to You and your Authorized Users and (ii) with your permission, to internally access, copy and use your Customer Content or Customer Application to review the underlying source code of your Customer Content or Customer Application for purposes of assisting You with de-bugging your Customer Content or Customer Application. You acknowledge and agree that the rights granted in (i) may be exercised by ExtensityAI’s third-party hosting provider in connection with their provision of hosting services to make the On-Premise Products available to You and your Authorized Users. - -6.3 RETENTION OF RIGHTS. ExtensityAI reserves all rights not expressly granted to You in this EULA. Without limiting the generality of the foregoing, You acknowledge and agree (i) that ExtensityAI and its third-party licensors retain all rights, title, and interest in and to the On-Premise Products; and (ii) that You do not acquire any rights, express or implied, in or to the foregoing, except as specifically set forth in this EULA and any Order Form. Any Feedback on the On-Premise Products suggested by You shall be free from any confidentiality restrictions that might otherwise be imposed upon ExtensityAI pursuant to Section 11 (Confidentiality) of this EULA and may be incorporated into the On-Premise Products by ExtensityAI. You acknowledge that the On-Premise Products incorporating any such new features, functionality, corrections, or enhancements shall be the sole and exclusive property of ExtensityAI. - -6.4 FEEDBACK. As an Authorized User of the On-Premise Products, You may provide suggestions, comments, feature requests or other feedback to any of ExtensityAI Materials or the On-Premise Products (“Feedback”). Such Feedback is deemed an integral part of ExtensityAI Materials, and as such, it is the sole property of ExtensityAI without restrictions or limitations on use of any kind. ExtensityAI may either implement or reject such Feedback, without any restriction or obligation of any kind. You (i) represent and warrant that such Feedback is accurate, complete, and does not infringe on any third-party rights; (ii) irrevocably assign to ExtensityAI any right, title, and interest You may have in such Feedback; and (iii) explicitly and irrevocably waive any and all claims relating to any past, present or future Intellectual Property Rights, or any other similar rights, worldwide, in or to such Feedback. - -7. CUSTOMER DATA, PRIVACY & SECURITY -7.1 YOUR CUSTOMER DATA. Your “Customer Data” is any data, files, attachments, text, images, reports, personal information, or any other data that is, uploaded or submitted, transmitted, or otherwise made available, to or through the On-Premise Products, by You or any of your Authorized Users and is processed by ExtensityAI on your behalf. For the avoidance of doubt, Anonymized Data is not regarded as Customer Data. You retain all right, title, interest, and control, in and to the Customer Data, in the form submitted to the On-Premise Products. Subject to this EULA, You grant ExtensityAI a worldwide, royalty-free non-exclusive license to store, access, use, process, copy, transmit, distribute, perform, export, and display the Customer Data, and solely to the extent that reformatting Customer Data for display in the On-Premise Products constitutes a modification or derivative work, the foregoing license also includes the right to make modifications and derivative works. The aforementioned license is hereby granted solely: (i) to maintain and provide You the On-Premise Products; (ii) to prevent or address technical or security issues and resolve support requests; (iii) to investigate when we have a good faith belief, or have received a complaint alleging, that such Customer Data is in violation of this EULA; (iv) to comply with a valid legal subpoena, request, or other lawful process; (v) to create Anonymized Data, and (vi) as expressly permitted in writing by You. - -7.2 NO SENSITIVE DATA. You shall not submit to the On-Premise Products any data that is protected under a special legislation and requires a unique treatment, including, without limitations, (i) categories of data enumerated in European Union Regulation 2016/679, Article 9(1) or any similar legislation or regulation in other jurisdiction; (ii) any protected health information subject to the Health Insurance Portability and Accountability Act (“HIPAA”), as amended and supplemented, or any similar legislation in other jurisdiction; and (iii) credit, debit or other payment card data subject to the Payment Card Industry Data Security Standard (“PCI DSS”) or any other credit card processing related requirements. - -7.3 PROCESSING CUSTOMER DATA. The ordinary operation of certain On-Premise Products requires Customer Data to pass through ExtensityAI’s network. To the extent that ExtensityAI processes Customer Data on your behalf that includes Personal Data, ExtensityAI will handle such Personal Data in compliance with our Data Processing Addendum. - -7.4 PRODUCT DATA. ExtensityAI retains all right, title, and interest in the models, observations, reports, analyses, statistics, databases and other information created, compiled, analyzed, generated or derived by ExtensityAI from platform, network, or traffic data generated by ExtensityAI in the course of providing the On-Premise Products (“Product Data”), and shall have the right to use Product Data for purposes of providing, maintaining, developing, and improving its On-Premise Products). ExtensityAI may monitor and inspect the traffic on the ExtensityAI network, including any related logs, as necessary to provide the On-Premise Products and to derive and compile threat data. To the extent the Product Data includes any Personal Data, ExtensityAI will handle such Personal Data in compliance with Applicable Data Protection Laws. ExtensityAI may use and retain your Account Information for business purposes related to this EULA and to the extent necessary to meet ExtensityAI’s legal compliance obligations (including, for audit and anti-fraud purposes). - -7.5 PRODUCT SECURITY. ExtensityAI will implement security safeguards for the protection of Customer Confidential Information, including any Customer Content originating or transmitted from or processed by the On-Premise Products and/or cached on or within ExtensityAI’s network and stored within the On-Premise Products in accordance with its policies and procedures. These safeguards include commercially reasonable administrative, technical, and organizational measures to protect Customer Content against destruction, loss, alteration, unauthorized disclosure, or unauthorized access, including such things as information security policies and procedures, security awareness training, threat and vulnerability management, incident response and breach notification, and vendor risk management procedures. ExtensityAI’s technical safeguards are further described in the Information Security Addendum. - -7.6 PRIVACY POLICY. As a part of accessing or using the On-Premise Products, we may collect, access, use and share certain Personal Data from, and/or about, You and your Users. Please read ExtensityAI’s Privacy Policy, which is incorporated herein by reference, for a description of such data collection and use practices in addition to those set forth herein. - -7.7 ANONYMIZED DATA. Notwithstanding any other provision of the EULA, we may collect, use, and publish Anonymized Data relating to your use of the On-Premise Products, and disclose it for the purpose of providing, improving, and publicizing our On-Premise Products, and for other business purposes. ExtensityAI owns all Anonymized Data collected or obtained by ExtensityAI. - -8. SUBSCRIPTION TERM, RENEWAL & FEES PAYMENT -8.1 ORDERS. Orders may be made in various ways, including through ExtensityAI’s online form or in-product screens or any other mutually agreed upon offline forms delivered by You or any of the other Users to ExtensityAI, including via mail, email or any other electronic or physical delivery mechanism (the “Order”). Such Order will list, at the least, the purchased On-Premise Products, Subscription Plan, Subscription Term, and the associated Subscription Fees. - -8.2 SUBSCRIPTION TERM. The On-Premise Products are provided on a subscription basis (“Subscription”) for the term specified in your Order (the “Subscription Term”), in accordance with the respective Plan purchased under such Order (the “Subscription Plan”). - -8.3 SUBSCRIPTION FEES; FEES FOR PROFESSIONAL SERVICES; SUPPORT FEES. In consideration for the provision of the On-Premise Products (except for Free Plans), You shall pay us the applicable fees per the purchased Subscription, as set forth in the applicable Order (the “Subscription Fees”). An Order can also include the provision of Professional Services, Support Services, and other services for the fees set forth in the Order (“Other Fees”). The Subscription Fees and Other Fees collectively form the “Fees”. Unless indicated otherwise, Fees are stated in US dollars. You hereby authorize ExtensityAI, either directly or through our payment processing service or our Affiliates, to charge such Fees via your selected payment method, upon the due date. Unless expressly set forth herein, the Subscription Fees are non-cancelable and non-refundable. We reserve the right to change the Fees at any time, upon notice to You if such change may affect your existing Subscriptions or other renewable services upon renewal. In the event of failure to collect the Fees You owe, we may, at our sole discretion (but shall not be obligated to), retry to collect at a later time, and/or suspend or cancel the Account, without notice. - -8.4 TAXES. The Fees are exclusive of any and all taxes (including without limitation, value added tax, sales tax, use tax, excise, goods and services tax, etc.), levies, or duties, which may be imposed in respect of this EULA and the purchase or sale, of the On-Premise Products or other services set forth in the Order (the “Taxes”), except for Taxes imposed on our income. If You are located in a jurisdiction which requires You to deduct or withhold Taxes or other amounts from any amounts due to ExtensityAI, please notify ExtensityAI, in writing, promptly and we shall join efforts to avoid any such Tax withholding, provided, however, that in any case, You shall bear the sole responsibility and liability to pay such Tax and such Tax should be deemed as being added on top of the Fees, payable by You. - -8.5 SUBSCRIPTION UPGRADE. During the Subscription Term, You may upgrade your Subscription Plan by either: (i) adding Authorized Users; (ii) upgrading to a higher type of Subscription Plan; (iii) adding add-on features and functionalities; and/or (iv) upgrading to a longer Subscription Term (collectively, “Subscription Upgrades”). Some Subscription Upgrades or other changes may be considered as a new purchase, hence will restart the Subscription Term and some will not, as indicated within the On-Premise Products and/or the Order. Upon a Subscription Upgrade, You will be billed for the applicable increased amount of Subscription Fees, at our then-current rates (unless indicated otherwise in an Order), either: (y) prorated for the remainder of the then-current Subscription Term, or (z) whenever the Subscription Term is being restarted due to the Subscription Upgrade, then the Subscription Fees already paid by You will be reduced from the new upgraded Subscription Fees, and the difference shall be due and payable by You upon the date on which the Subscription Upgrade was made. - -8.6 ADDING USERS. You acknowledge that, unless You disable these options, then use of some On-Premise Products may allow: (i) Authorized Users within the same email domain may be able to automatically join the Account; and (ii) Authorized Users within your Account may invite other persons to be added to the Account as Authorized Users (each, a “User Increase”). For further information on these options and how to disable them, visit our Support Center. Unless agreed otherwise in an Order, any changes to the number of Authorized Users within a certain Account, shall be billed on a prorated basis for the remainder of the then-current Subscription Term. We will bill You, either upon the User Increase or at the end of the applicable month, as communicated to You. - -8.7 EXCESSIVE USAGE. We shall have the right, including without limitation where we, at our sole discretion, believe that You and/or any of your Authorized Users, have misused the On-Premise Products or otherwise use the On-Premise Products in an excessive manner compared to the anticipated standard use (at our sole discretion) to: (a) offer the Subscription in different pricing and/or (b) impose additional restrictions as for the upload, storage, download and use of the On-Premise Products, including, without limitation, restrictions on Third-Party Services, network traffic and bandwidth, size and/or length of Content, quality and/or format of Content, sources of Content, volume of download time, etc. - -8.8 BILLING. As part of registering, submitting billing information, or agreeing to an Order You agree to provide us with updated, accurate, and complete billing information, and You authorize us (either directly or through our Affiliates or other third parties) to charge, request, and collect payment (or otherwise charge, refund, or take any other billing actions) from your payment method or designated banking account, and to make any inquiries that we (or our Affiliates and/or third-parties acting on our behalf) may consider necessary to validate your designated payment account or financial information, in order to ensure prompt payment. - -8.9 SUBSCRIPTION AUTO-RENEWAL. In order to ensure that You will not experience any interruption or loss of services, your Subscriptions and Support Services include an automatic renewal option by default, according to which, unless You opt-out of auto-renewal or cancel your Subscription or Support Services prior to their expiration, the Subscription or Support Services will automatically renew upon the end of the then applicable term, for a renewal period equal in time to the original term (excluding extended periods) and, unless otherwise notified to You, at no more (subject to applicable Tax changes and excluding any discount or other promotional offer provided for the first term). Accordingly, unless either You or ExtensityAI cancel the Subscription or Support Services or other renewable service contract prior to its expiration, we will attempt to automatically charge You the applicable Fees upon or immediately prior to the expiration of the then applicable term. If You wish to avoid such auto-renewal, You shall cancel your Subscription (or opt-out of auto-renewal), prior to the expiration of the current term, at any time through the Account settings, or by contacting our Customer Success team. Except as expressly set forth in this EULA, in case You cancel your Subscription or other renewable service, during a term, the service will not renew for an additional period, but You will not be refunded or credited for any unused period within current term. Unless expressly stated otherwise in a separate legally binding agreement, if You received a special discount or other promotional offer, You acknowledge that upon renewal of your Subscription or other renewable service, ExtensityAI will renew , at the full applicable Fee at the time of renewal. - -8.10 CREDITS. If and to the extent any credits may accrue to your Account, for any reason (the “Credits”), will expire and be of no further force and effect, upon the earlier of: (i) the expiration or termination of the applicable Subscription under the Account for which such Credits were given; or (ii) in case such Credits accrued for an Account with a Free Plan that was not upgraded to a Paid Plan, then upon the lapse of ninety (90) days of such Credits’ accrual. Unless specifically indicated otherwise, Credits may be used to pay for the On-Premise Products only and not for any Third-Party Service or other payment of whatsoever kind. Whenever fees are due for any On-Premise Products, accrued Credits will be first reduced against the Subscription Fees and the remainder will be charged from your respective payment method. Credits shall have no monetary value (except for the purchase of On-Premise Products under the limited terms specified herein), nor exchange value, and will not be transferable or refundable. - -8.11 PAYMENT THROUGH RESELLER. If You purchased On-Premise Products from a reseller or distributor authorized by ExtensityAI (each, an “Reseller”), then to the extent there is any conflict between this EULA and any terms of service entered between You and the respective Reseller, including any purchase order (“Reseller Agreement”), then, as between You and ExtensityAI, this EULA shall prevail. Any rights granted to You and/or any of the other Users in such Reseller Agreement which are not contained in this EULA, apply only in connection with the Reseller. In that case, You must seek redress or realization or enforcement of such rights solely with the Reseller and not ExtensityAI. For clarity, You and your Authorized Users’ access to the On-Premise Products is subject to our receipt from Reseller of the payment of the applicable Fees paid by You to Reseller. You hereby acknowledge that at any time, at our discretion, the billing of the Fees may be assigned to us, such that You shall pay us directly the respective Fees. - -9. REFUNDS; CHARGEBACKS -9.1 REFUND POLICY. If You are not satisfied with your initial purchase of an On-Premise Product, You may terminate such On-Premise Product by providing us a written notice, within thirty (30) days of having first ordered such On-Premise Products (the “Refund Period”). If You terminate such initial purchase of an On-Premise Product, within the Refund Period, we will refund You the pro-rata portion of any unused and unexpired Fees pre-paid by You in respect of such terminated period of the Subscription, unless such other sum is required by applicable law, in U.S. Dollars (the “Refund”). The Refund is applicable only to the initial purchase of the On-Premise Products by You and does not apply to any additional purchases, upgrades, modifications, or renewals of such On-Premise Products. Please note that we shall not be responsible to Refund any differences caused by change of currency exchange rates or fees that You were charged by third parties, such as wire transfer fees. After the Refund Period, the Subscription Fees are non-refundable and non-cancellable. To the extent permitted by law, if we find that a notice of cancellation has been given in bad faith or in an illegitimate attempt to avoid payment for On-Premise Products actually received and enjoyed, we reserve our right to reject your Refund request. Subject to the foregoing, upon termination by You under this Section 9.1 all outstanding payment obligations shall immediately become due for the used Subscription Term, and You will promptly remit to ExtensityAI any Fees due to ExtensityAI under this EULA. - -9.2 NON-REFUNDABLE ON-PREMISE PRODUCTS. Certain On-Premise Products may be non-refundable. In such event we will identify such On-Premise Products as non-refundable, and You shall not be entitled, and we shall not be under any obligation, to terminate the On-Premise Products and give a Refund. - -9.3 CHARGEBACK. If, at any time, we record a decline, chargeback, or other rejection of a charge of any due and payable Fees on your Account (“Chargeback”), this will be considered as a breach of your payment obligations hereunder, and your use of the On-Premise Products may be disabled or terminated and such use of the On-Premise Products will not resume until You re-subscribe for any such On-Premise Products, and pay any applicable Fees in full, including any fees and expenses incurred by us and/or any Third-Party Service for each Chargeback received (including handling and processing charges and fees incurred by the payment processor), without derogating from any other remedy that may be applicable to us under this EULA or applicable law. - -10. TERM AND TERMINATION; SUSPENSION -10.1 TERM. This EULA is in full force and effect, commencing as between You and ExtensityAI upon the Effective Date, until your usage or receipt of services is terminated or expires. - -10.2 TERMINATION FOR CAUSE. Either You or ExtensityAI may terminate the On-Premise Products and this EULA, upon written notice, in case that (a) the other Party is in material breach of this EULA and to the extent curable, fails to cure such breach, within a reasonable cure period, which shall not be less than ten (10) days following a written notice from by the non-breaching Party; provided ExtensityAI may terminate immediately to prevent immediate harm to the On-Premise Products or to prevent violation of its rights of confidentiality or Intellectual Property Rights; or (b) ceases its business operations or becomes subject to insolvency proceedings and the proceedings are not dismissed within forty-five (45) days. - -10.3 TERMINATION BY YOU. You may terminate your Subscription to the On-Premise Products by cancelling the On-Premise Products and/or deleting the Account, whereby such termination shall not derogate from your obligation to pay applicable fees except as otherwise provided herein. In accordance with Section 9 (Refunds; Chargebacks), unless mutually agreed otherwise by You and ExtensityAI in a written instrument, the effective date of such termination will take effect at the end of the then-current term, and your obligation to pay the fees throughout the end of such term shall remain in full force and effect, and You shall not be entitled to a refund for any pre-paid fees. - -10.4 EFFECT OF TERMINATION OF SUBSCRIPTION. Upon termination or expiration of this EULA, your Subscription and all rights granted to You hereunder shall terminate, and we may change the Account’s access settings. It is your sole liability to export the Customer Data or Customer Content prior to such termination or expiration. In the event that You did not delete the Customer Data or Customer Content from the Account, we may continue to store and host it until either You or we, at our sole discretion, delete such Customer Data or Customer Content, and during such period, You shall still be able to make a limited use of the On-Premise Products in order to export the Customer Data or Customer Content (the “Read-Only Mode”), but note that we are not under any obligation to maintain the Read-Only Mode period, hence such period may be terminated by us, at any time, with or without notice to You, and subsequently, the Customer Data or Customer Content will be deleted. You acknowledge the foregoing and your sole responsibility to export and/or delete the Customer Data or Customer Content prior to the termination or expiration of this EULA, and therefore we shall not have any liability either to You, nor to any Authorized User or third party, in connection thereto. Unless expressly indicated herein otherwise, the termination or expiration of this EULA shall not relieve You from your obligation to pay any Fees due and payable to ExtensityAI. - -10.5 SURVIVAL. Section 1.1(a)(iv) (Free Plan Terms), 2.4 (Additional Policies), 4.4 (Your Warranties), 5 (Your Responsibilities & Restrictions), 6 (Intellectual Property & Ownership), 7 (Customer Data, Privacy & Security), 8 (Subscription Term, Renewal and Fees Payment) in respect of unpaid Subscription Fees, 108 (Term and Termination; Suspension), 11 (Confidentiality), 12.2 (Disclaimers), 12.3 (Remedies), 12.4 (Restrictions), 13 (Limitations of Liability), 14 (Indemnification), and 15 (General Provisions), shall survive the termination or expiration of this EULA, and continue to be in force and effect in accordance with their applicable terms. - -10.6 SUSPENSION. Without derogating from our termination rights above, we may decide to temporarily suspend the Account and/or an Authorized User (including any access thereto) and/or our On-Premise Products, in the following events: (i) we believe, at our sole discretion, that You or any third party, are using the On-Premise Products in a manner that may impose a security risk, may cause harm to us or any third party, and/or may raise any liability for us or any third party; (ii) we believe, at our sole discretion, that You or any third party, are using the On-Premise Products in breach of this EULA or applicable Law; (iii) your payment obligations, in accordance with this EULA, are or are likely to become, overdue; or (iv) You or any of your Users’ breach of the Acceptable Use Policy. The aforementioned suspension rights are in addition to any remedies that may be available to us in accordance with this EULA and/or applicable Law. - -11. CONFIDENTIALITY -11.1 CONFIDENTIAL INFORMATION. In connection with this EULA and the On-Premise Products (including the evaluation thereof), each Party (“Discloser”) may disclose to the other Party (“Recipient”), non-public business, product, technology and marketing information, including without limitation, customers lists and information, know-how, software and any other non-public information that is either identified as such or should reasonably be understood to be confidential given the nature of the information and the circumstances of disclosure, whether disclosed prior or after the Effective Date (“Confidential Information”). For the avoidance of doubt, (i) Customer Data is regarded as your Confidential Information, and (ii) our On-Premise Products, including Trial Offerings and/or Pre-Released Offerings, and inclusive of their underlying technology, and their respective performance information, as well as any data, reports, and materials we provided to You in connection with your evaluation or use of the On-Premise Products, are regarded as our Confidential Information. Confidential Information does not include information that (a) is or becomes generally available to the public without breach of any obligation owed to the Discloser; (b) was known to the Recipient prior to its disclosure by the Discloser without breach of any obligation owed to the Discloser; (c) is received from a third party without breach of any obligation owed to the Discloser; or (d) was independently developed by the Recipient without any use or reference to the Confidential Information. - -11.2 CONFIDENTIALITY OBLIGATIONS. The Recipient will (i) take at least reasonable measures to prevent the unauthorized disclosure or use of Confidential Information, and limit access to those employees, affiliates, service providers and agents, on a need to know basis and who are bound by confidentiality obligations at least as restrictive as those contained herein; and (ii) not use or disclose any Confidential Information to any third party, except as part of its performance under this EULA and as required to be disclosed to legal or financial advisors to the Recipient or in connection with a due diligence process that the Recipient is undergoing, provided that any such disclosure shall be governed by confidentiality obligations at least as restrictive as those contained herein. - -11.3 COMPELLED DISCLOSURE. Notwithstanding the above, Confidential Information may be disclosed pursuant to the order or requirement of a court, administrative agency, or other governmental body; provided, however, that to the extent legally permissible, the Recipient shall make best efforts to provide prompt written notice of such court order or requirement to the Discloser to enable the Discloser to seek a protective order or otherwise prevent or restrict such disclosure. - -12. WARRANTIES, REMEDIES, AND DISCLAIMERS. -12.1 ON-PREMISE PRODUCTS WARRANTY. - -a. OUR ON-PREMISE PRODUCTS WARRANTY. ExtensityAI warrants to You that, during the Subscription Term, the On-Premise Products will perform in material conformity with the functions described in the applicable Documentation. Such warranty period shall not apply to Free Plans and Subscriptions offered for no fee. ExtensityAI will use commercially reasonable efforts to remedy any material non-conformity with respect to On-Premise Products at no additional charge to You. - -b. REMEDY FOR NON-CONFORMANCE. In the event ExtensityAI is unable to remedy the non-conformity in Section 12.1(a) of this EULA within a commercially reasonable period of time, and such non-conformity materially and adversely affects the functionality of the On-Premise Products, You may promptly terminate the applicable Subscription upon written notice to ExtensityAI and a thirty (30) day period to cure. In the event You terminate your Subscription pursuant to this Section 12.1, You will receive a Refund of any prepaid and unused portion of the Subscription Fees paid. The foregoing shall constitute your exclusive remedy, and ExtensityAI’s entire liability, with respect to any breach of this Section 12.1 (On-Premise Products Warranty). - -c. LIMITED THIRD-PARTY SERVICE WARRANTY. ExtensityAI warrants to You that to the extent any Third-Party Service is used in the On-Premise Products, ExtensityAI has the right to grant You the license to use the Third-Party Service. - -12.2 DISCLAIMERS. EXCEPT AS SET FORTH IN THE FOREGOING LIMITED WARRANTY IN SECTION 12.1, THE ON-PREMISE PRODUCTS ARE PROVIDED "AS IS" AND ExtensityAI AND OUR LICENSORS DISCLAIM ALL OTHER WARRANTIES AND REPRESENTATIONS, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE, AND EXPRESSLY DISCLAIM THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ExtensityAI DOES NOT REPRESENT OR WARRANT THAT THE ON-PREMISE PRODUCTS ARE ERROR FREE OR THAT ALL ERRORS CAN BE CORRECTED. EXCEPT AS EXPRESSLY SET FORTH HEREIN, WE DO NOT WARRANT, AND EXPRESSLY DISCLAIM ANY WARRANTY OR REPRESENTATION (I) THAT OUR ON-PREMISE PRODUCTS (OR ANY PORTION THEREOF) ARE COMPLETE, ACCURATE, OF ANY CERTAIN QUALITY, RELIABLE, SUITABLE FOR, OR COMPATIBLE WITH, ANY OF YOUR CONTEMPLATED ACTIVITIES, DEVICES, OPERATING SYSTEMS, BROWSERS, SOFTWARE OR TOOLS (OR THAT IT WILL REMAIN AS SUCH AT ANY TIME), OR COMPLY WITH ANY LAWS APPLICABLE TO YOU; AND/OR (II) REGARDING ANY CONTENT, INFORMATION, REPORTS, OR RESULTS THAT YOU OBTAIN THROUGH THE ON-PREMISE PRODUCTS. THE ON-PREMISE PRODUCTS ARE NOT DESIGNED, INTENDED, OR LICENSED FOR USE IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE CONTROLS, INCLUDING WITHOUT LIMITATION, THE DESIGN, CONSTRUCTION, MAINTENANCE, OR OPERATION OF NUCLEAR FACILITIES, AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, AND LIFE SUPPORT OR WEAPONS SYSTEMS. ExtensityAI SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR SUCH PURPOSES. No oral or written information or advice given by ExtensityAI, its Resellers, Partners, dealers, distributors, agents, representatives, or Personnel shall create any warranty or in any way increase any warranty provided herein. - -12.3 REMEDIES. Except with respect to the Free Plans for which ExtensityAI provides no representations, warranties, or covenants, your exclusive remedy for ExtensityAI's breach of the foregoing warranties is that ExtensityAI will, at our option and at no cost to You, either (a) provide remedial services necessary to enable the On-Premise Products to conform to the warranty, or (b) replace any defective On-Premise Products. If neither of the foregoing options is commercially feasible within a reasonable period of time, upon your return of the affected On-Premise Products to ExtensityAI, ExtensityAI will refund all prepaid fees for the unused remainder of the applicable Subscription Term following the date of termination for the affected On-Premise Products and this EULA and any associated Orders for the affected On-Premise Products will immediately terminate without further action of the Parties. You agree to provide ExtensityAI with a reasonable opportunity to remedy any breach and reasonable assistance in remedying any nonconformities. - -12.4 RESTRICTIONS. If applicable law requires any warranties other than the foregoing, all such warranties are limited in duration to ninety (90) days from the date of delivery. Some jurisdictions do not allow the exclusion of implied warranties, so the above exclusion may not apply to You. The warranty provided herein gives You specific legal rights and You may also have other legal rights that vary from jurisdiction to jurisdiction. The limitations or exclusions of warranties, remedies or liability contained in this EULA shall apply to You only to the extent such limitations or exclusions are permitted under the laws of the jurisdiction where You are located. - -13. LIMITATION OF LIABILITY. -13.1 LIMITATIONS. NOTWITHSTANDING ANYTHING IN THIS EULA OR ELSEWHERE TO THE CONTRARY AND TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW: - -a. IN NO EVENT, EXCEPT IN THE CASE OF A BREACH OF CONFIDENTIALITY OBLIGATIONS OR EXTENSITYAI’S INTELLECTUAL PROPERTY RIGHTS, SHALL EITHER PARTY HERETO AND ITS AFFILIATES, SUBCONTRACTORS, AGENTS AND VENDORS (INCLUDING, THE THIRD PARTY SERVICE PROVIDERS), BE LIABLE UNDER, OR OTHERWISE IN CONNECTION WITH THIS EULA FOR (I) ANY INDIRECT, EXEMPLARY, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES; (II) ANY LOSS OF PROFITS, COSTS, ANTICIPATED SAVINGS; (III) ANY LOSS OF, OR DAMAGE TO DATA, USE, BUSINESS, REPUTATION, REVENUE OR GOODWILL; AND/OR (IV) THE FAILURE OF SECURITY MEASURES AND PROTECTIONS, WHETHER IN CONTRACT, TORT OR UNDER ANY OTHER THEORY OF LIABILITY OR OTHERWISE, AND WHETHER OR NOT SUCH PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES IN ADVANCE, AND EVEN IF A REMEDY FAILS OF ITS ESSENTIAL PURPOSE. - -b. EXCEPT FOR THE INDEMNITY OBLIGATIONS OF EITHER PARTY UNDER SECTION 14 (INDEMNIFICATION) HEREIN, YOUR PAYMENT OBLIGATIONS HEREUNDER, A VIOLATION OF EXTENSITYAI’S INTELLECTUAL PROPERTY RIGHTS OR BREACH OF OUR ACCEPTABLE USE POLICY BY EITHER YOU OR ANY OF THE AUTHORIZED USERS UNDERLYING YOUR ACCOUNT, IN NO EVENT SHALL THE TOTAL AGGREGATE LIABILITY OF EITHER PARTY, ITS AFFILIATES, SUBCONTRACTORS, AGENTS AND VENDORS (INCLUDING, THE ITS THIRD-PARTY SERVICE PROVIDERS), UNDER, OR OTHERWISE IN CONNECTION WITH, THIS EULA (INCLUDING THE ON-PREMISE PRODUCTS), EXCEED THE TOTAL AMOUNT OF FEES ACTUALLY PAID BY YOU (IF ANY) DURING THE TWELVE (12) CONSECUTIVE MONTHS PRECEDING THE EVENT GIVING RISE TO SUCH LIABILITY. THIS LIMITATION OF LIABILITY IS CUMULATIVE AND NOT PER INCIDENT. - -13.2 SPECIFIC LAWS. Except as expressly stated in this EULA, we make no representations or warranties that your use of the On-Premise Products is appropriate in your jurisdiction. Other than as indicated herein, You are responsible for your compliance with any local and/or specific applicable Laws, as applicable to your use of the On-Premise Products. - -13.3 REASONABLE ALLOCATION OF RISKS. You hereby acknowledge and confirm that the limitations of liability and warranty disclaimers contained in this EULA are agreed upon by You and ExtensityAI and we both find such limitations and allocation of risks to be commercially reasonable and suitable for our engagement hereunder, and both You and ExtensityAI have relied on these limitations and risk allocation in determining whether to enter this EULA. - -14. INDEMNIFICATION. -14.1 BY YOU. You hereby agree to indemnify, defend and hold harmless ExtensityAI and our Affiliates, officers, directors, employees and agents from and against any and all claims, damages, obligations, liabilities, losses, reasonable expenses or costs (collectively, “Losses”) incurred as a result of any third party claim arising from (i) You and/or any of your Authorized Users’, violation of this EULA or applicable law; and/or (ii) Bundled Products, Customer Data and/or Customer Content, including the use of Bundled Products, Customer Data and/or Customer Content by ExtensityAI and/or any of our subcontractors, which infringes or violates, any third party’s rights, including, without limitation, Intellectual Property Rights. - -14.2 BY ExtensityAI. - -a. ExtensityAI hereby agrees to defend You, your Affiliates, officers, directors, and employees, in and against any third party claim or demand against You, alleging that your authorized use of the On-Premise Products infringes or constitutes misappropriation of any third party’s copyright, trademark or registered U.S. patent (the “IP Claim”), and we will indemnify You and hold You harmless against any damages and costs finally awarded on such IP Claim by a court of competent jurisdiction or agreed to via settlement we agreed upon, including reasonable attorneys’ fees. - -b. ExtensityAI’s indemnity obligations under Section 14.2(a) shall not apply if: (i) the On-Premise Products (or any portion thereof) were modified by You or any of your Authorized Users or any third party, but solely to the extent the IP Claim would have been avoided by not doing such modification; (ii) if the On-Premise Products are used in combination with any other service, device, software or products, including, without limitation, Third-Party Content or Third-Party Services, but solely to the extent that such IP Claim would have been avoided without such combination; and/or (iii) any IP Claim arising or related to, Third Party Content, Third Party Services, Customer Data, Customer Content, or to any events giving rise to your indemnity obligations under Section 14.1 above. Without derogating from the foregoing defense and indemnification obligation, if ExtensityAI believes that the On-Premise Products, or any part thereof, may so infringe, then ExtensityAI may in our sole discretion: (a) obtain (at no additional cost to You) the right to continue to use the On-Premise Products; (b) replace or modify the allegedly infringing part of the On-Premise Products so that it becomes non-infringing while giving substantially equivalent performance; or (c) if ExtensityAI determines that the foregoing remedies are not reasonably available, then ExtensityAI may require that use of the (allegedly) infringing On-Premise Products (or part thereof) shall cease and in such an event, You shall receive a prorated refund of any Subscription Fees paid for the unused portion of the Subscription Term. THIS SECTION 14.2 STATES EXTENSITYAI’S SOLE AND ENTIRE LIABILITY AND YOUR EXCLUSIVE REMEDY, FOR ANY INTELLECTUAL PROPERTY INFRINGEMENT OR MISAPPROPRIATION BY ExtensityAI AND/OR OUR ON-PREMISE PRODUCTS, AND UNDERLYING ExtensityAI MATERIALS. - -14.3 INDEMNITY CONDITIONS. The defense and indemnification obligations of the indemnifying Party (“Indemnitor”) under this Section 14 are subject to: (i) the indemnified Party (“Indemnitee”) shall promptly provide a written notice of the claim for which an indemnification is being sought, provided that such Indemnitee’s failure to do so will not relieve the Indemnitor of its obligations under this Section 14.3, except to the extent the Indemnitor’s defense is materially prejudiced thereby; (ii) the Indemnitor being given immediate and exclusive control over the defense and/or settlement of the claim, provided, however that the Indemnitor shall not enter into any compromise or settlement of any such claim that that requires any monetary obligation or admission of liability or any unreasonable responsibility or liability by an Indemnitee without the prior written consent of the affected Indemnitee, which shall not be unreasonably withheld or delayed; and (iii) the Indemnitee providing reasonable cooperation and assistance, at the Indemnitor’s expense, in the defense and/or settlement of such claim and not taking any action that prejudices the Indemnitor’s defense of, or response to, such claim. - -15. GENERAL PROVISIONS. -15.1 GOVERNING LAW; JURISDICTION. This EULA and any action related thereto will be governed and interpreted by and under the laws of the State of Texas without giving effect to any conflicts of laws principles that require the application of the law of a different jurisdiction. Courts of competent jurisdiction located in Austin, Texas, shall have the sole and exclusive jurisdiction and venue over all controversies and claims arising out of, or relating to, this EULA. You and ExtensityAI mutually agree that the United Nations Convention on Contracts for the International Sale of Goods does not apply to this EULA. Notwithstanding the foregoing, ExtensityAI reserves the right to seek injunctive relief in any court in any jurisdiction. - -15.2 EXPORT CONTROLS; SANCTIONS. The On-Premise Products may be subject to U.S. or foreign export controls, laws and regulations (the “Export Controls”), and You acknowledge and confirm that: (i) You are not located in and will not use, export, re-export or import the On-Premise Products (or any portion thereof) in or to, any person, entity, organization, jurisdiction or otherwise, in violation of the Export Controls; (ii) You are not: (a) organized under the laws of, operating from, or otherwise ordinarily resident in a country or territory that is the target or comprehensive U.S. economic or trade sanctions (currently, Cuba, Iran, Syria, North Korea, or the Crimea region of Ukraine), (b) identified on a list of prohibited or restricted persons, such as the U.S. Treasury Department’s List of Specially Designated Nationals and Blocked Persons, or (c) otherwise the target of U.S. sanctions. You are solely responsible for complying with applicable Export Controls and sanctions which may impose additional restrictions, prohibitions or requirements on the use, export, re-export or import of the On-Premise Products, Customer Content or Customer Data; and (iii) Customer Content and/or Customer Data is not controlled under the U.S. International Traffic in Arms Regulations or similar Laws in other jurisdictions, or otherwise requires any special permission or license, in respect of its use, import, export or re-export hereunder. - -15.3 GOVERNMENT USE. If You are part of a U.S. Government agency, department or otherwise, either federal, state, or local (a “Government Customer”), then Government Customer hereby agrees that the On-Premise Products under this EULA qualifies as “Commercial Computer Software” and “Commercial Computer Software Documentation”, within the meaning of Federal Acquisition Regulation (“FAR”) 2.101, FAR 12.212, Defense Federal Acquisition Regulation Supplement (“DFARS”) 227.7201, and DFARS 252.227-7014. Government Customer further agrees that the terms of this Section 20 shall apply to You. Government Customer’s technical data and software rights related to the On-Premise Products include only those rights customarily provided to the public as specified in this EULA in accordance with FAR 12.212, FAR 27.405-3, FAR 52.227-19, DFARS 227.7202-1 and General Services Acquisition Regulation (“GSAR”) 552.212-4(w) (as applicable). In no event shall source code be provided or considered to be a deliverable or a software deliverable under this EULA. We grant no license whatsoever to any Government Customer to any source code contained in any deliverable or a software deliverable. If a Government Customer has a need for rights not granted under this EULA, it must negotiate with ExtensityAI to determine if there are acceptable terms for granting those rights, and a mutually acceptable written addendum specifically granting those rights must be included in any applicable agreement. Any unpublished rights are reserved under applicable copyright laws. Any provisions contained in this EULA that contradict any law(s) applicable to a Government Customer, shall be limited solely to the extent permitted under such applicable law(s). - -15.4 TRANSLATED VERSIONS. This EULA were written in English, and the EULA may be translated into other languages for your convenience. If a translated (non-English) version of this EULA conflicts in any way with their English version, the provisions of the English version shall prevail. - -15.5 FORCE MAJEURE. Neither You nor ExtensityAI will be liable by reason of any failure or delay in the performance of its obligations on account of an event of Force Majeure; provided the foregoing shall not remove liability for Your failure to pay fees when due and payable. Force Majeure includes, but is not restricted to, events of the following types (but only to the extent that such an event, in consideration of the circumstances, satisfies the requirements of the Definition): acts of God; civil disturbance; sabotage; strikes; lock-outs; work stoppages; action or restraint by court order or public or government authority (as long as the affected Party has not applied for or assisted in the application for, and has opposed to the extent reasonable, such court or government action). - -15.6 RELATIONSHIP OF THE PARTIES; NO THIRD-PARTY BENEFICIARIES. The Parties are independent contractors. This EULA and the On-Premise Products provided hereunder, do not create a partnership, franchise, joint venture, agency, fiduciary or employment relationship between the Parties. There are no third-party beneficiaries to this EULA. - -15.7 MODIFICATIONS. We will also notify You of changes to this EULA by posting an updated version at https://extensity.ai and revising the “Last Updated” date therein. We encourage You to periodically review this EULA to be informed with respect to You and ExtensityAI’s rights and obligations with respect to the On-Premise Products. Using the On-Premise Products after a notice of changes has been sent to You or published in the On-Premise Products shall constitute consent to the changed terms and practices. - -15.8 NOTICES. We shall use your contact details that we have in our records, in connection with providing You notices, subject to this Section 15.8. Our contact details for any notices are detailed below. You acknowledge notices that we provide You, in connection with this EULA and/or as otherwise related to the On-Premise Products, shall be provided as follows: via the On-Premise Products, including by posting on our Platform or posting in your Account, text, in-app notification, e-mail, phone or first class, airmail, or overnight courier. You further acknowledge that an electronic notification satisfies any applicable legal notification requirements, including that such notification will be in writing. Any notice to You will be deemed given upon the earlier of: (i) receipt; or (ii) twenty-four (24) hours of delivery. Notices to us shall be provided to ExtensityAI, Inc., Attn: Legal, at 1108 Lavaca St. Ste 110-645, Austin, Texas 78701 and office@extensity.ai. - -15.9 ASSIGNMENT. This EULA, and any and all rights and obligations hereunder, may not be transferred or assigned by You without our written approval, provided that You may assign this EULA to your successor entity or person, resulting from a merger, acquisition, or sale of all or substantially all of your assets or voting rights, except for an assignment to a competitor of ExtensityAI, and provided that You provide us with prompt written notice of such assignment and the respective assignee agrees, in writing, to assume all of your obligations under this EULA. We may assign our rights and/or obligations hereunder and/or transfer ownership rights and title in the On-Premise Products to a third party without your consent or prior notice to You. Subject to the foregoing conditions, this EULA shall bind and inure to the benefit of the Parties, their respective successors, and permitted assigns. Any assignment not authorized under this Section 15.9 shall be null and void. - -15.10 PUBLICITY. ExtensityAI reserves the right to reference You as a customer and display your logo and name on our website and other promotional materials for marketing purposes. Any display of your logo and name shall be in compliance with your branding guidelines, if provided by You. In case You do not agree to such use of the logo and/or name, ExtensityAI must be notified in writing. Except as provided in Section 15.10 of the EULA, neither Party will use the logo, name or trademarks of the other Party or refer to the other Party in any form of publicity or press release without such Party’s prior written approval. - -15.11 CHILDREN AND MINORS. If You are under 18 years old, then by entering into these Terms You explicitly stipulate that (i) You have legal capacity to consent to These Terms or that You have valid consent from a parent or legal guardian to do so and (ii) You understand the ExtensityAI Privacy Policy. You may not enter into this EULA if You are under 13 years old. IF YOU DO NOT UNDERSTAND THIS SECTION, DO NOT UNDERSTAND THE ExtensityAI PRIVACY POLICY, OR DO NOT KNOW WHETHER YOU HAVE THE LEGAL CAPACITY TO ACCEPT THIS EULA, PLEASE ASK YOUR PARENT OR LEGAL GUARDIAN FOR HELP. - -15.12 ENTIRE AGREEMENT. This EULA (including all Orders) constitutes the entire agreement, and supersedes all prior negotiations, understandings, or agreements (oral or written), between the Parties regarding the subject matter of this EULA (and all past dealing or industry custom). Any inconsistent or additional terms on any related Customer-issued purchase orders, vendor forms, invoices, policies, confirmation, or similar form, even if signed by the Parties hereafter, will have no effect under this EULA. In the event of any conflict between the terms of this EULA and the terms of any Order, the terms of this EULA will control unless otherwise explicitly set forth in an Order. This EULA may be executed in one or more counterparts, each of which will be an original, but taken together constituting one and the same instrument. Execution of a facsimile/electronic copy will have the same force and effect as execution of an original, and a facsimile/electronic signature will be deemed an original and valid signature. No modification, consent or waiver under this EULA will be effective unless in writing and signed by both Parties. The failure of either Party to enforce its rights under this EULA at any time for any period will not be construed as a waiver of such rights. If any provision of this EULA is determined to be illegal or unenforceable, that provision will be limited or eliminated to the minimum extent necessary so that this EULA will otherwise remain in full force and effect and enforceable. diff --git a/symbolicai-main/symbolicai-main/symai/__init__.py b/symbolicai-main/symbolicai-main/symai/__init__.py deleted file mode 100644 index e87706c7efd2bba67bc92f7adf6905abc938b5a0..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/__init__.py +++ /dev/null @@ -1,362 +0,0 @@ -import json -import logging -import os -import subprocess -import sys -import warnings -from pathlib import Path - -from rich import print as rprint -from rich.console import Console -from rich.panel import Panel -from rich.table import Table -from rich.tree import Tree - -from .backend import settings -from .menu.screen import show_menu -from .misc.console import ConsoleStyle -from .utils import CustomUserWarning - -# do not remove - hides the libraries' debug messages -logging.getLogger("urllib3").setLevel(logging.WARNING) -logging.getLogger("requests").setLevel(logging.WARNING) -logging.getLogger("tika").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) -logging.getLogger("huggingface_hub").setLevel(logging.ERROR) -logging.getLogger("huggingface").setLevel(logging.ERROR) -logging.getLogger('pydub').setLevel(logging.ERROR) - -warnings.simplefilter("ignore") - -# set the environment variable for the transformers library -os.environ['TOKENIZERS_PARALLELISM'] = "false" - -# Create singleton instance -config_manager = settings.SymAIConfig() - -SYMAI_VERSION = "0.13.1" -__version__ = SYMAI_VERSION -__root_dir__ = config_manager.config_dir - -def _start_symai(): - global _symai_config_ - global _symsh_config_ - global _symserver_config_ - - # Create config directories if they don't exist - os.makedirs(config_manager._env_config_dir, exist_ok=True) - os.makedirs(config_manager._home_config_dir, exist_ok=True) - - # CREATE THE SHELL CONFIGURATION FILE IF IT DOES NOT EXIST YET - # *==============================================================================================================* - _symsh_config_path_ = config_manager.get_config_path('symsh.config.json') - if not os.path.exists(_symsh_config_path_): - config_manager.save_config('symsh.config.json', { - "colors": { - "completion-menu.completion.current": "bg:#323232 #212121", - "completion-menu.completion": "bg:#800080 #212121", - "scrollbar.background": "bg:#222222", - "scrollbar.button": "bg:#776677", - "history-completion": "bg:#212121 #f5f5f5", - "path-completion": "bg:#800080 #f5f5f5", - "file-completion": "bg:#9040b2 #f5f5f5", - "history-completion-selected": "bg:#efefef #b3d7ff", - "path-completion-selected": "bg:#efefef #b3d7ff", - "file-completion-selected": "bg:#efefef #b3d7ff" - }, - "map-nt-cmd": True, - "show-splash-screen": True, - "plugin_prefix": None - }) - - # CREATE A SERVER CONFIGURATION FILE IF IT DOES NOT EXIST YET - # *==============================================================================================================* - _symserver_config_path_ = config_manager.get_config_path('symserver.config.json') - if not os.path.exists(_symserver_config_path_): - config_manager.save_config('symserver.config.json', {}) - - # Get appropriate config path (debug mode handling is now in config_manager) - _symai_config_path_ = config_manager.get_config_path('symai.config.json') - - if not os.path.exists(_symai_config_path_): - setup_wizard(_symai_config_path_, show_wizard=False) - CustomUserWarning(f'No configuration file found for the environment. A new configuration file has been created at {_symai_config_path_}. Please configure your environment.') - sys.exit(1) - - # Load and manage configurations - _symai_config_ = config_manager.load_config('symai.config.json') - _tmp_symai_config_ = _symai_config_.copy() - - # MIGRATE THE ENVIRONMENT VARIABLES - # *==========================================================================================================* - if 'SPEECH_ENGINE_MODEL' in _symai_config_: - updates = { - 'SPEECH_TO_TEXT_ENGINE_MODEL': _symai_config_['SPEECH_ENGINE_MODEL'], - 'TEXT_TO_SPEECH_ENGINE_MODEL': "tts-1" - } - config_manager.migrate_config('symai.config.json', updates) - del _symai_config_['SPEECH_ENGINE_MODEL'] - del _tmp_symai_config_['SPEECH_ENGINE_MODEL'] - - if 'COLLECTION_URI' not in _symai_config_: - updates = { - 'COLLECTION_URI': "mongodb+srv://User:vt3epocXitd6WlQ6@extensityai.c1ajxxy.mongodb.net/?retryWrites=true&w=majority", - 'COLLECTION_DB': "ExtensityAI", - 'COLLECTION_STORAGE': "SymbolicAI", - 'SUPPORT_COMMUNITY': False - } - config_manager.migrate_config('symai.config.json', updates) - with ConsoleStyle('info') as console: - msg = 'Currently you are sharing your user experience with us by uploading the data to our research server, and thereby helping us improve future models and the overall SymbolicAI experience. We thank you very much for supporting the research community! If you wish to disable the data collection option go to your .symai config situated in your home directory or set the environment variable `SUPPORT_COMMUNITY` to `False`.' - console.print(msg) - - # POST-MIGRATION CHECKS - # *==============================================================================================================* - if 'TEXT_TO_SPEECH_ENGINE_API_KEY' not in _symai_config_: - updates = { - 'TEXT_TO_SPEECH_ENGINE_API_KEY': _symai_config_.get('NEUROSYMBOLIC_ENGINE_API_KEY', '') - } - config_manager.migrate_config('symai.config.json', updates) - - # Load all configurations - _symai_config_ = config_manager.load_config('symai.config.json') - _symsh_config_ = config_manager.load_config('symsh.config.json') - _symserver_config_ = config_manager.load_config('symserver.config.json') - - # MIGRATE THE SHELL SPLASH SCREEN CONFIGURATION - # *==============================================================================================================* - if 'show-splash-screen' not in _symsh_config_: - config_manager.migrate_config('symsh.config.json', {'show-splash-screen': True}) - - # CHECK IF THE USER HAS A NEUROSYMBOLIC API KEY - # *==============================================================================================================* - if not ( - _symai_config_['NEUROSYMBOLIC_ENGINE_MODEL'].lower().startswith('llama') or \ - _symai_config_['NEUROSYMBOLIC_ENGINE_MODEL'].lower().startswith('huggingface')) \ - and \ - ( - _symai_config_['NEUROSYMBOLIC_ENGINE_API_KEY'] is None or \ - len(_symai_config_['NEUROSYMBOLIC_ENGINE_API_KEY']) == 0): - # Try to fallback to the global (home) config if environment is not home - if config_manager.config_dir != config_manager._home_config_dir: - CustomUserWarning(f"You didn't configure your environment ({config_manager.config_dir})! Falling back to the global ({config_manager._home_config_dir}) configuration if it exists.") - # Force loading from home - _symai_config_ = config_manager.load_config('symai.config.json', fallback_to_home=True) - _symsh_config_ = config_manager.load_config('symsh.config.json', fallback_to_home=True) - _symserver_config_ = config_manager.load_config('symserver.config.json', fallback_to_home=True) - - # If still not valid, warn and exit - if not _symai_config_.get('NEUROSYMBOLIC_ENGINE_API_KEY'): - CustomUserWarning('The mandatory neuro-symbolic engine is not initialized. Please set NEUROSYMBOLIC_ENGINE_MODEL and NEUROSYMBOLIC_ENGINE_API_KEY.') - sys.exit(1) - - settings.SYMAI_CONFIG = _symai_config_ - settings.SYMSH_CONFIG = _symsh_config_ - settings.SYMSERVER_CONFIG = _symserver_config_ - -def run_setup_wizard(file_path = None): - if file_path is None: - file_path = config_manager.get_config_path('symai.config.json') - setup_wizard(file_path) - - -def run_server(): - _symserver_config_ = {} - if settings.SYMAI_CONFIG.get("NEUROSYMBOLIC_ENGINE_MODEL").startswith("llama") or settings.SYMAI_CONFIG.get("EMBEDDING_ENGINE_MODEL").startswith("llama"): - from .server.llama_cpp_server import llama_cpp_server - - command, args = llama_cpp_server() - _symserver_config_.update(zip(args[::2], args[1::2])) - _symserver_config_['online'] = True - - config_manager.save_config("symserver.config.json", _symserver_config_) - - try: - subprocess.run(command, check=True) - except KeyboardInterrupt: - print("Server stopped!") - except Exception as e: - print(f"Error running server: {e}") - finally: - config_manager.save_config("symserver.config.json", {'online': False}) - - elif settings.SYMAI_CONFIG.get("NEUROSYMBOLIC_ENGINE_MODEL").startswith("huggingface"): - from .server.huggingface_server import huggingface_server - - command, args = huggingface_server() - _symserver_config_.update(vars(args)) - _symserver_config_['online'] = True - - config_manager.save_config("symserver.config.json", _symserver_config_) - - try: - command(host=args.host, port=args.port) - except KeyboardInterrupt: - print("Server stopped!") - except Exception as e: - print(f"Error running server: {e}") - finally: - config_manager.save_config("symserver.config.json", {'online': False}) - else: - raise CustomUserWarning("You're trying to run a local server without a valid neuro-symbolic engine model. Please set a valid model in your configuration file. Current available options are 'llamacpp' and 'huggingface'.") - - -# *==============================================================================================================* -def format_config_content(config: dict) -> str: - """Format config content for display, truncating API keys.""" - formatted = {} - for k, v in config.items(): - if isinstance(v, str) and ('KEY' in k or 'URI' in k) and v: - # Show first/last 4 chars of keys/URIs - formatted[k] = f"{v[:4]}...{v[-4:]}" if len(v) > 8 else v - else: - formatted[k] = v - return json.dumps(formatted, indent=2) - -def display_config(): - """Display all configuration paths and their content.""" - - console = Console() - - # Create header - console.print(Panel.fit( - f"[bold cyan]SymbolicAI Configuration Inspector v{__version__}[/bold cyan]", - border_style="cyan" - )) - - # Create main tree - tree = Tree("[bold]Configuration Locations[/bold]") - - # Debug config - debug_branch = tree.add("[yellow]Debug Mode Config (CWD)[/yellow]") - debug_config = config_manager._debug_dir / 'symai.config.json' - if debug_config.exists(): - with open(debug_config) as f: - content = json.load(f) - debug_branch.add(f"📄 [green]{debug_config}[/green]\n{format_config_content(content)}") - else: - debug_branch.add("[dim]No debug config found[/dim]") - - # Environment config - env_branch = tree.add("[yellow]Environment Config[/yellow]") - env_configs = { - 'symai.config.json': '⚙️', - 'symsh.config.json': '🖥️', - 'symserver.config.json': '🌐' - } - - for config_file, icon in env_configs.items(): - config_path = config_manager._env_config_dir / config_file - if config_path.exists(): - with open(config_path) as f: - content = json.load(f) - env_branch.add(f"{icon} [green]{config_path}[/green]\n{format_config_content(content)}") - else: - env_branch.add(f"[dim]{icon} {config_file} (not found)[/dim]") - - # Home (global) config - home_branch = tree.add("[yellow]Home Directory Config (Global)[/yellow]") - for config_file, icon in env_configs.items(): - config_path = config_manager._home_config_dir / config_file - if config_path.exists(): - with open(config_path) as f: - content = json.load(f) - home_branch.add(f"{icon} [green]{config_path}[/green]\n{format_config_content(content)}") - else: - home_branch.add(f"[dim]{icon} {config_file} (not found)[/dim]") - - # Active configuration summary - summary = Table(show_header=True, header_style="bold magenta") - summary.add_column("Configuration Type") - summary.add_column("Active Path") - - active_paths = { - "Primary Config Dir": config_manager.config_dir, - "symai.config.json": config_manager.get_config_path('symai.config.json'), - "symsh.config.json": config_manager.get_config_path('symsh.config.json'), - "symserver.config.json": config_manager.get_config_path('symserver.config.json') - } - - for config_type, path in active_paths.items(): - summary.add_row(config_type, str(path)) - - # Print everything - console.print(tree) - console.print("\n[bold]Active Configuration Summary:[/bold]") - console.print(summary) - - # Print help - console.print("\n[bold]Legend:[/bold]") - console.print("⚙️ symai.config.json (Main SymbolicAI configuration)") - console.print("🖥️ symsh.config.json (Shell configuration)") - console.print("🌐 symserver.config.json (Server configuration)") - console.print("\n[dim]Note: API keys and URIs are truncated for security[/dim]") -# *==============================================================================================================* - - -def setup_wizard(_symai_config_path_, show_wizard=True): - _user_config_ = show_menu(show_wizard=show_wizard) - _nesy_engine_api_key = _user_config_['nesy_engine_api_key'] - _nesy_engine_model = _user_config_['nesy_engine_model'] - _symbolic_engine_api_key = _user_config_['symbolic_engine_api_key'] - _symbolic_engine_model = _user_config_['symbolic_engine_model'] - _embedding_engine_api_key = _user_config_['embedding_engine_api_key'] - _embedding_model = _user_config_['embedding_model'] - _drawing_engine_api_key = _user_config_['drawing_engine_api_key'] - _drawing_engine_model = _user_config_['drawing_engine_model'] - _vision_engine_model = _user_config_['vision_engine_model'] - _search_engine_api_key = _user_config_['search_engine_api_key'] - _search_engine_model = _user_config_['search_engine_model'] - _ocr_engine_api_key = _user_config_['ocr_engine_api_key'] - _speech_to_text_engine_model = _user_config_['speech_to_text_engine_model'] - _text_to_speech_engine_api_key = _user_config_['text_to_speech_engine_api_key'] - _text_to_speech_engine_model = _user_config_['text_to_speech_engine_model'] - _text_to_speech_engine_voice = _user_config_['text_to_speech_engine_voice'] - _indexing_engine_api_key = _user_config_['indexing_engine_api_key'] - _indexing_engine_environment = _user_config_['indexing_engine_environment'] - _caption_engine_environment = _user_config_['caption_engine_environment'] - _support_comminity = _user_config_['support_community'] - - config_manager.save_config(_symai_config_path_, { - "NEUROSYMBOLIC_ENGINE_API_KEY": _nesy_engine_api_key, - "NEUROSYMBOLIC_ENGINE_MODEL": _nesy_engine_model, - "SYMBOLIC_ENGINE_API_KEY": _symbolic_engine_api_key, - "SYMBOLIC_ENGINE": _symbolic_engine_model, - "EMBEDDING_ENGINE_API_KEY": _embedding_engine_api_key, - "EMBEDDING_ENGINE_MODEL": _embedding_model, - "DRAWING_ENGINE_API_KEY": _drawing_engine_api_key, - "DRAWING_ENGINE_MODEL": _drawing_engine_model, - "VISION_ENGINE_MODEL": _vision_engine_model, - "SEARCH_ENGINE_API_KEY": _search_engine_api_key, - "SEARCH_ENGINE_MODEL": _search_engine_model, - "OCR_ENGINE_API_KEY": _ocr_engine_api_key, - "SPEECH_TO_TEXT_ENGINE_MODEL": _speech_to_text_engine_model, - "TEXT_TO_SPEECH_ENGINE_API_KEY": _text_to_speech_engine_api_key, - "TEXT_TO_SPEECH_ENGINE_MODEL": _text_to_speech_engine_model, - "TEXT_TO_SPEECH_ENGINE_VOICE": _text_to_speech_engine_voice, - "INDEXING_ENGINE_API_KEY": _indexing_engine_api_key, - "INDEXING_ENGINE_ENVIRONMENT": _indexing_engine_environment, - "CAPTION_ENGINE_MODEL": _caption_engine_environment, - "COLLECTION_URI": "mongodb+srv://User:vt3epocXitd6WlQ6@extensityai.c1ajxxy.mongodb.net/?retryWrites=true&w=majority", - "COLLECTION_DB": "ExtensityAI", - "COLLECTION_STORAGE": "SymbolicAI", - "SUPPORT_COMMUNITY": _support_comminity - }) - - -_start_symai() - -from .backend.base import Engine -from .components import Function, PrimitiveDisabler -from .core import few_shot, zero_shot -from .extended import Conversation -from .functional import EngineRepository -from .imports import Import -from .interfaces import Interface -from .post_processors import PostProcessor -from .pre_processors import PreProcessor -from .prompts import Prompt, PromptLanguage, PromptRegistry -from .shell import Shell -from .strategy import Strategy -from .symbol import Call, Expression, GlobalSymbolPrimitive, Metadata, Symbol diff --git a/symbolicai-main/symbolicai-main/symai/backend/__init__.py b/symbolicai-main/symbolicai-main/symai/backend/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/symbolicai-main/symbolicai-main/symai/backend/base.py b/symbolicai-main/symbolicai-main/symai/backend/base.py deleted file mode 100644 index 284b5447d26bce9ed0c286d5013b34516d8a92d1..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/base.py +++ /dev/null @@ -1,195 +0,0 @@ -import logging -import os -import time - -from abc import ABC -from typing import Any, List, Tuple -from .settings import HOME_PATH - -from ..collect import CollectionRepository, rec_serialize - - -ENGINE_UNREGISTERED = '' - -class Engine(ABC): - def __init__(self) -> None: - super().__init__() - self.verbose = False - self.logging = False - self.log_level = logging.DEBUG - self.time_clock = False - self.collection = CollectionRepository() - self.collection.connect() - # create formatter - __root_dir__ = HOME_PATH - os.makedirs(__root_dir__, exist_ok=True) - __file_path__ = __root_dir__ / "engine.log" - logging.basicConfig(filename=__file_path__, filemode="a", format='%(asctime)s %(name)s %(levelname)s %(message)s') - self.logger = logging.getLogger() - self.logger.setLevel(logging.DEBUG) - # logging to console - stream = logging.StreamHandler() - streamformat = logging.Formatter("%(asctime)s %(message)s") - stream.setLevel(logging.INFO) - stream.setFormatter(streamformat) - self.logger.addHandler(stream) - - def __call__(self, argument: Any) -> Tuple[List[str], dict]: - log = { - 'Input': { - 'self': self, - 'args': argument.args, - **argument.kwargs - } - } - start_time = time.time() - - # check for global object based input handler - if hasattr(argument.prop.instance, '_metadata') and hasattr(argument.prop.instance._metadata, 'input_handler'): - input_handler = argument.prop.instance._metadata.input_handler if hasattr(argument.prop.instance._metadata, 'input_handler') else None - if input_handler is not None: - input_handler((argument.prop.processed_input, argument)) - # check for kwargs based input handler - if argument.prop.input_handler is not None: - argument.prop.input_handler((argument.prop.processed_input, argument)) - - # execute the engine - res, metadata = self.forward(argument) - - # compute time - req_time = time.time() - start_time - metadata['time'] = req_time - if self.time_clock: - print(f"{argument.prop.func}: {req_time} sec") - log['Output'] = res - if self.verbose: - view = {k: v for k, v in list(log['Input'].items()) if k != 'self'} - input_ = f"{str(log['Input']['self'])[:50]}, {str(argument.prop.func)}, {str(view)}" - print(input_[:150], str(log['Output'])[:100]) - if self.logging: - self.logger.log(self.log_level, log) - - # share data statistics with the collection repository - if str(self) == 'GPTXChatEngine' \ - or str(self) == 'GPTXCompletionEngine' \ - or str(self) == 'SerpApiEngine' \ - or str(self) == 'WolframAlphaEngine' \ - or str(self) == 'SeleniumEngine' \ - or str(self) == 'OCREngine': - self.collection.add( - forward={'args': rec_serialize(argument.args), 'kwds': rec_serialize(argument.kwargs)}, - engine=str(self), - metadata={ - 'time': req_time, - 'data': rec_serialize(metadata), - 'argument': rec_serialize(argument) - } - ) - - # check for global object based output handler - if hasattr(argument.prop.instance, '_metadata') and hasattr(argument.prop.instance._metadata, 'output_handler'): - output_handler = argument.prop.instance._metadata.output_handler if hasattr(argument.prop.instance._metadata, 'output_handler') else None - if output_handler: - output_handler(res) - # check for kwargs based output handler - if argument.prop.output_handler: - argument.prop.output_handler((res, metadata)) - return res, metadata - - def id(self) -> str: - return ENGINE_UNREGISTERED - - def preview(self, argument): - # used here to avoid circular import - from ..symbol import Symbol - class Preview(Symbol): - def __repr__(self) -> str: - ''' - Get the representation of the Symbol object as a string. - - Returns: - str: The representation of the Symbol object. - ''' - return str(self.value.prop.prepared_input) - - def prepared_input(self): - return self.value.prop.prepared_input - - return Preview(argument), {} - - def forward(self, *args: Any, **kwds: Any) -> List[str]: - raise NotADirectoryError() - - def prepare(self, argument): - raise NotImplementedError() - - def command(self, *args, **kwargs): - if kwargs.get('verbose', None): - self.verbose = kwargs['verbose'] - if kwargs.get('logging', None): - self.logging = kwargs['logging'] - if kwargs.get('log_level', None): - self.log_level = kwargs['log_level'] - if kwargs.get('time_clock', None): - self.time_clock = kwargs['time_clock'] - - def __str__(self) -> str: - return self.__class__.__name__ - - def __repr__(self) -> str: - ''' - Get the representation of the Symbol object as a string. - - Returns: - str: The representation of the Symbol object. - ''' - # class with full path - class_ = self.__class__.__module__ + '.' + self.__class__.__name__ - hex_ = hex(id(self)) - return f'' - - -class BatchEngine(Engine): - def __init__(self): - super().__init__() - self.time_clock = True - self.allows_batching = True - - def __call__(self, arguments: List[Any]) -> List[Tuple[Any, dict]]: - start_time = time.time() - for arg in arguments: - if hasattr(arg.prop.instance, '_metadata') and hasattr(arg.prop.instance._metadata, 'input_handler'): - input_handler = getattr(arg.prop.instance._metadata, 'input_handler', None) - if input_handler is not None: - input_handler((arg.prop.processed_input, arg)) - if arg.prop.input_handler is not None: - arg.prop.input_handler((arg.prop.processed_input, arg)) - - try: - results, metadata_list = self.forward(arguments) - except Exception as e: - results = [e] * len(arguments) - metadata_list = [None] * len(arguments) - - total_time = time.time() - start_time - if self.time_clock: - print(f"Total execution time: {total_time} sec") - - return_list = [] - - for arg, result, metadata in zip(arguments, results, metadata_list): - if metadata is not None: - metadata['time'] = total_time / len(arguments) - - if hasattr(arg.prop.instance, '_metadata') and hasattr(arg.prop.instance._metadata, 'output_handler'): - output_handler = getattr(arg.prop.instance._metadata, 'output_handler', None) - if output_handler: - output_handler(result) - if arg.prop.output_handler: - arg.prop.output_handler((result, metadata)) - - return_list.append((result, metadata)) - return return_list - - def forward(self, arguments: List[Any]) -> Tuple[List[Any], List[dict]]: - raise NotImplementedError("Subclasses must implement forward method") diff --git a/symbolicai-main/symbolicai-main/symai/backend/driver/webclient.py b/symbolicai-main/symbolicai-main/symai/backend/driver/webclient.py deleted file mode 100644 index e9cddd2efc6de8e790da231db83ab29e9d552de1..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/driver/webclient.py +++ /dev/null @@ -1,217 +0,0 @@ -import os - -os.environ['WDM_LOG'] = 'false' # disable webdriver-manager logging - -import logging - -logging.getLogger('WDM').setLevel(logging.NOTSET) - -import random -import re -import sys -import time -import urllib.request -import warnings - -from random import choice - -try: - warnings.filterwarnings('ignore', module='chromedriver') - warnings.filterwarnings('ignore', module='selenium') - from selenium import webdriver - from selenium.webdriver.remote.remote_connection import LOGGER - from webdriver_manager.firefox import GeckoDriverManager - from selenium.webdriver.firefox.options import Options as FirefoxOptions - from selenium.webdriver.firefox.service import Service as FirefoxService - from webdriver_manager.chrome import ChromeDriverManager - from selenium.webdriver.chrome.options import Options as ChromeOptions - from selenium.webdriver.chrome.service import Service as ChromeService - from webdriver_manager.microsoft import EdgeChromiumDriverManager - from selenium.webdriver.edge.options import Options as EdgeOptions - from selenium.webdriver.edge.service import Service as EdgeService - from selenium.common.exceptions import WebDriverException - - LOGGER.setLevel(logging.ERROR) - -except Exception as e: - webdriver = None - if "No module named 'selenium'" in str(e): - print(f"ERROR: {e}") - print(f"ERROR: Please install selenium with `pip install selenium`") - else: - print(f"ERROR: {e}") - -from ... import __root_dir__ - - -class Proxy(object): - def __init__(self, host, port): - self.host = host - self.port = port - - -class add_path(): - def __init__(self, path): - self.path = path - - def __enter__(self): - sys.path.insert(0, self.path) - - def __exit__(self, exc_type, exc_value, traceback): - try: - sys.path.remove(self.path) - except ValueError: - pass - - -def wait_for(condition_function, timeout): - start_time = time.time() - while time.time() < start_time + timeout: - if condition_function(): - return True - else: - time.sleep(0.1) - raise Exception(f'Server does not respond to request with appropriate content. Check link or script.') - - -class page_loaded(object): - def __init__(self, driver, check_pattern, timeout=3, debug=False): - self.check_pattern = check_pattern - self.driver = driver - self.timeout = timeout - self.debug = debug - - def __enter__(self): - pass - - def page_has_loaded(self): - if self.debug: print(self.driver.page_source) - return re.search(self.check_pattern, self.driver.page_source) - - def __exit__(self, *_): - wait_for(self.page_has_loaded, timeout=self.timeout) - - -def add_options(options, proxy): - if proxy: options.add_argument(f"--proxy-server=socks5://{proxy.host}:{proxy.port}") - options.add_argument('--ignore-certificate-errors') - options.add_argument('--incognito') - options.add_argument("--headless") - options.add_argument("--log-level=3") - - -def _connect_brower(debug, proxy=None): - assert webdriver is not None, "selenium is not installed" - - try: - options = ChromeOptions() - add_options(options, proxy) - driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=options) - except Exception as e1: - try: - print(f"ERROR REMEDY: Trying to use Chrome as an alternative.") - options = FirefoxOptions() - add_options(options, proxy) - driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()), options=options) - except Exception as e2: - print(f"Issue with finding an appropriate driver version. Your current browser might be newer than the driver. Please either downgrade Chrome or try to install a proper chromedriver manually.\nOriginal error: {e1}; Remedy attempt error: {e2}") - try: - print(f"ERROR REMEDY: Trying to use Edge as an alternative.") - options = EdgeOptions() - if proxy: options.add_argument(f"--proxy-server=socks5://{proxy.host}:{proxy.port}") - add_options(options, proxy) - driver = webdriver.Edge(service=EdgeService(EdgeChromiumDriverManager().install()), options=options) - except Exception as e3: - print(f"Issue with finding an appropriate driver version. Your current browser might be newer than the driver. Please either downgrade Chrome or try to install a proper chromedriver manually.\nOriginal error: {e1}; Remedy attempt error: {e2}; Second remedy attempt error: {e3}") - raise e3 from e2 - if debug: print("Chrome Headless Browser Invoked") - - return driver - - -def connect_browsers(debug, proxy): - assert webdriver is not None, "selenium is not installed" - class BrowserHandler(object): - def __init__(self, debug): - self.browsers = [_connect_brower(debug, proxy=proxy)] - def __call__(self): - return choice(self.browsers) - return BrowserHandler(debug) - - -def dump_page_source(driver, file_path="dump.log"): - with open(file_path, "wb") as err_file: - err_file.write(driver.page_source.encode("utf-8")) - - - -def contains_text(check_pattern, search_pattern, link, driver_handler, script=None, debug=False, args=None): - driver = driver_handler() - try: - driver.get(link) - except WebDriverException as e: - print(f"ERROR: {e}") - print(f"ERROR: Please install a proper driver for your browser. You can find the appropriate driver here: https://selenium-python.readthedocs.io/installation.html#drivers") - return False - with page_loaded(driver, check_pattern, debug=debug): - if script is not None: script(driver, args) - rsp = re.search(search_pattern, driver.page_source) - return True if rsp else False - - -def download_images(driver, args): - src = driver.find_element_by_xpath("//div[@class='bRMDJf islir']/descendant-or-self::*[img]").get_attribute("src") - imgs = driver.find_elements_by_tag_name('img') - p = args[0] - uri = [] - for i in imgs: - data = i.get_attribute("src") - if data and data.startswith('data'): - response = urllib.request.urlopen(data) - n = i.get_attribute("data-iml") - if n: - if not os.path.exists(f'data/{p}'): - os.makedirs(f'data/{p}') - with open(f'data/{p}/{n}.jpg', 'wb') as f: - f.write(response.file.read()) - - -def run_selenium_test(debug=False): - proxy = Proxy(host="localhost", port=9050) - driver_handler = connect_browsers(debug, proxy) - - max_cnt = 5 - cnt = 0 - now = time.time() - - with open('data/text_demo.txt', 'r') as f: - text = f.read().replace('\n', '')\ - .replace('.', '')\ - .replace(',', '') - - print(text) - #text = "women sitting in the park" #names.get_full_name() - - # input String - lst = text.split(' ') - - while cnt < max_cnt: - start_pos = random.randint(0, len(lst)-1) - len_ = random.randint(1, 6) - seq = lst[start_pos:start_pos+len_] - pattern = " ".join(seq) - result = contains_text(check_pattern="Images", - search_pattern=pattern, - link=f"https://www.google.com/search?tbm=isch&as_q={pattern}&tbs=isz:lt,islt:4mp,sur:fmc", - driver_handler=driver_handler, - debug=True, - script=download_images, - args=[pattern]) - timestamp = time.time() - now - now = time.time() - print(f"{result} - time: {timestamp}") - cnt += 1 - - -if __name__ == "__main__": - run_selenium_test(debug=True) diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/__init__.py b/symbolicai-main/symbolicai-main/symai/backend/engines/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/crawler/engine_selenium.py b/symbolicai-main/symbolicai-main/symai/backend/engines/crawler/engine_selenium.py deleted file mode 100644 index fffef91630aebca27fed97594e9b8a55ae65c3fd..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/crawler/engine_selenium.py +++ /dev/null @@ -1,94 +0,0 @@ -from typing import Callable -from bs4 import BeautifulSoup - -from ...base import Engine -from ...driver.webclient import connect_browsers, dump_page_source, page_loaded -from ....symbol import Result - - -class SeleniumResult(Result): - def __init__(self, value, **kwargs) -> None: - super().__init__(value, **kwargs) - if value is not None: - self.raw = value - self._value = self.extract() - - def extract(self): - tmp = self.value if isinstance(self.value, list) else [self.value] - res = [] - for r in tmp: - if r is None: - continue - soup = BeautifulSoup(r, 'html.parser') - text = soup.getText() - res.append(text) - res = None if len(res) == 0 else '\n'.join(res) - return res - - -class SeleniumEngine(Engine): - def __init__(self, debug: bool = False): - super().__init__() - self.debug = debug - self.driver_handler = None - self.name = self.__class__.__name__ - - def _init_crawler_engine(self): - self.driver_handler = connect_browsers(debug=False, proxy=None) - - def get_page_source(self, url: str, pattern: str, script: Callable = None) -> str: - # deprecated - driver = self.driver_handler() - try: - driver.get(url) - with page_loaded(driver, pattern, debug=self.debug): - if script: driver.execute_script(script) - return driver.page_source - except Exception as ex: - if self.debug: dump_page_source(driver) - if self.debug: print(ex) - return f"Sorry, I cannot find the page you are looking for: {ex}" - - def id(self) -> str: - return 'crawler' - - def forward(self, argument): - urls, patterns = argument.prop.prepared_input - urls = urls if isinstance(urls, list) else [urls] - - patterns = patterns if isinstance(patterns, list) else [patterns] - assert len(urls) == len(patterns) - rsp = [] - - self._init_crawler_engine() - - for url, p in zip(urls, patterns): - page = self.get_page_source(url=url, pattern=p) - rsp.append(page) - - metadata = {} - rsp = SeleniumResult(rsp) - return [rsp], metadata - - def prepare(self, argument): - assert not argument.prop.processed_input, "CrawlerEngine does not support processed_input." - assert argument.prop.urls, "CrawlerEngine requires urls." - - argument.prop.urls = [str(argument.prop.url)] - argument.prop.patterns = [str(argument.prop.pattern)] - - # be tolerant to kwarg or arg and assign values of urls and patterns - # assign urls - if len(argument.args) >= 1: - argument.prop.urls = argument.args[0] - elif len(argument.kwargs) >= 1: - keys = list(argument.kwargs.keys()) - argument.prop.urls = argument.kwargs[keys[0]] - # assign patterns - if len(argument.args) >= 2: - argument.prop.patterns = argument.args[1] - elif len(argument.kwargs) >= 2: - keys = list(argument.kwargs.keys()) - argument.prop.patterns = argument.kwargs[keys[1]] - - argument.prop.prepared_input = (argument.prop.urls, argument.prop.patterns) diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/drawing/engine_bfl.py b/symbolicai-main/symbolicai-main/symai/backend/engines/drawing/engine_bfl.py deleted file mode 100644 index 0030ddde80981a472c4a3e086ddde604b7a6e201..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/drawing/engine_bfl.py +++ /dev/null @@ -1,125 +0,0 @@ -import logging -import tempfile -import time -from typing import Optional - -import requests - -from ....symbol import Result -from ...base import Engine -from ...settings import SYMAI_CONFIG - -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - - -class FluxResult(Result): - def __init__(self, value, **kwargs): - super().__init__(value, **kwargs) - # unpack the result - path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name - url = value.get('result').get('sample') - request = requests.get(url, allow_redirects=True) - request.raise_for_status() - with open(path, "wb") as f: - f.write(request.content) - self._value = [path] - - -class DrawingEngine(Engine): - def __init__(self, api_key: Optional[str] = None, model: Optional[str] = None): - super().__init__() - self.config = SYMAI_CONFIG - self.api_key = self.config['DRAWING_ENGINE_API_KEY'] if api_key is None else api_key - self.model = self.config['DRAWING_ENGINE_MODEL'] if model is None else model - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config['DRAWING_ENGINE_API_KEY'] and self.config['DRAWING_ENGINE_MODEL'].startswith("flux"): - return 'drawing' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'DRAWING_ENGINE_API_KEY' in kwargs: - self.api_key = kwargs['DRAWING_ENGINE_API_KEY'] - if 'DRAWING_ENGINE_MODEL' in kwargs: - self.model = kwargs['DRAWING_ENGINE_MODEL'] - - def forward(self, argument): - prompt = argument.prop.prepared_input - kwargs = argument.kwargs - model = kwargs.get('model', self.model) - width = kwargs.get('width', 1024) - height = kwargs.get('height', 768) - steps = kwargs.get('steps', 40) - prompt_upsampling = kwargs.get('prompt_upsampling', False) - seed = kwargs.get('seed', None) - guidance = kwargs.get('guidance', None) - safety_tolerance = kwargs.get('safety_tolerance', 2) - interval = kwargs.get('interval', None) - output_format = kwargs.get('output_format', 'png') - except_remedy = kwargs.get('except_remedy', None) - - headers = { - 'accept': 'application/json', - 'x-key': self.api_key, - 'Content-Type': 'application/json', - } - - payload = { - 'prompt': prompt, - 'width': width, - 'height': height, - 'num_inference_steps': steps, - 'guidance_scale': guidance, - 'seed': seed, - 'safety_tolerance': safety_tolerance, - } - # drop any None values so Flux API won't return 500 - payload = {k: v for k, v in payload.items() if v is not None} - - if kwargs.get('operation') == 'create': - try: - response = requests.post( - f'https://api.us1.bfl.ai/v1/{self.model}', - headers=headers, - json=payload - ) - # fail early on HTTP errors - response.raise_for_status() - data = response.json() - request_id = data.get("id") - if not request_id: - raise Exception(f"Failed to get request ID! Response payload: {data}") - - while True: - time.sleep(5) - - result = requests.get( - 'https://api.us1.bfl.ai/v1/get_result', - headers=headers, - params={'id': request_id} - ) - - result.raise_for_status() - result = result.json() - - if result["status"] == "Ready": - rsp = FluxResult(result) - break - - except Exception as e: - if except_remedy is None: - raise e - rsp = except_remedy(self, e, None, argument) - - metadata = {} - return [rsp], metadata - else: - raise Exception(f"Unknown operation: {kwargs['operation']}") - - def prepare(self, argument): - argument.prop.prepared_input = str(argument.prop.processed_input) diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/drawing/engine_gpt_image.py b/symbolicai-main/symbolicai-main/symai/backend/engines/drawing/engine_gpt_image.py deleted file mode 100644 index b93189725b8bca505f9e1cd1227b7561247304b3..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/drawing/engine_gpt_image.py +++ /dev/null @@ -1,201 +0,0 @@ -import base64 -import logging -import tempfile -from pathlib import Path -from typing import Optional - -import openai -import requests - -from ....symbol import Result -from ...base import Engine -from ...settings import SYMAI_CONFIG - -# silence noisy libraries -logging.getLogger("openai").setLevel(logging.ERROR) -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - - -class GPTImageResult(Result): - """ - Wraps an OpenAI images.generate / edit / variation response. - Exposes .value as the raw response and ._value as the - first URL or decoded b64 image string. - """ - def __init__(self, value, **kwargs): - super().__init__(value, **kwargs) - imgs = [] - for item in value.data: - has_url = hasattr(item, "url") - has_b64 = hasattr(item, "b64_json") - path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name - if has_url and item.url is not None: - request = requests.get(item.url, allow_redirects=True) - request.raise_for_status() - with open(path, "wb") as f: - f.write(request.content) - elif has_b64 and item.b64_json is not None: - raw = base64.b64decode(item.b64_json) - with open(path, "wb") as f: - f.write(raw) - imgs.append(path) - self._value = imgs - - -class GPTImageEngine(Engine): - """ - A drop‐in engine for OpenAI's unified Images API, - supporting gpt-image-1, dall-e-2, dall-e-3, - with all the extra parameters (background, moderation, etc). - """ - def __init__( - self, - api_key: Optional[str] = None, - model: Optional[str] = None, - ): - super().__init__() - self.config = SYMAI_CONFIG - # pick up a separate config slot if you like, or fall back - openai.api_key = ( - self.config.get("DRAWING_ENGINE_API_KEY") - if api_key is None - else api_key - ) - self.model = ( - self.config.get("DRAWING_ENGINE_MODEL") - if model is None - else model - ) - self.name = self.__class__.__name__ - # quiet OpenAI's internal logger - log = logging.getLogger("openai") - log.setLevel(logging.WARNING) - - def id(self) -> str: - # register this engine under "gpt-image" by default - cfg_model = self.config.get("DRAWING_ENGINE_MODEL") - if cfg_model.startswith("gpt-image-") or cfg_model.startswith("dall-e-"): - return "drawing" - return super().id() - - def command(self, *args, **kwargs): - """ - Allow hot‐swapping API key or model at runtime. - """ - super().command(*args, **kwargs) - if "DRAWING_ENGINE_API_KEY" in kwargs: - openai.api_key = kwargs["DRAWING_ENGINE_API_KEY"] - if "DRAWING_ENGINE_MODEL" in kwargs: - self.model = kwargs["DRAWING_ENGINE_MODEL"] - - def prepare(self, argument): - """ - Simply copy processed_input → prepared_input - """ - argument.prop.prepared_input = str(argument.prop.processed_input) - - def forward(self, argument): - prompt = argument.prop.prepared_input - kwargs = argument.kwargs - - model = kwargs.get("model", self.model) - operation = kwargs.get("operation") - - if operation is None: - raise ValueError("Operation not specified!") - - n = kwargs.get("n", 1) - - if "size" in kwargs: - s = kwargs["size"] - kwargs["size"] = f"{s}x{s}" - - except_remedy = kwargs.get("except_remedy", None) - - callback = None - try: - if operation == "create": - create_kwargs = { - "model": model, - "prompt": prompt, - "n": n, - "size": kwargs.get("size"), - } - - if model == "dall-e-3": - create_kwargs["response_format"] = kwargs.get("response_format", "url") - create_kwargs["quality"] = kwargs.get("quality", "standard") - create_kwargs["style"] = kwargs.get("style", "vivid") - - if model.startswith("gpt-image-"): - create_kwargs["quality"] = kwargs.get("quality", "medium") - create_kwargs["moderation"] = kwargs.get("moderation", "auto") - create_kwargs["background"] = kwargs.get("background", "auto") - create_kwargs["output_format"] = kwargs.get("output_compression", "png") - if create_kwargs["output_format"] == "jpeg" or create_kwargs["output_format"] == "webp": - create_kwargs["output_compression"] = kwargs.get("output_compression", "100") - - callback = openai.images.generate - res = openai.images.generate(**create_kwargs) - - elif operation == "variation": - assert "image_path" in kwargs, "image_path required for variation" - callback = openai.images.create_variation - with open(kwargs["image_path"], "rb") as img: - res = openai.images.create_variation( - model=model, - image=img, - n=n, - size=kwargs.get("size"), - response_format=kwargs.get("response_format", "url"), - ) - - elif operation == "edit": - assert "image_path" in kwargs, "image_path required for edit" - # allow either a single path or a list of paths - img_paths = kwargs["image_path"] - if not isinstance(img_paths, (list, tuple)): - img_paths = [img_paths] - # open all images - image_files = [open(p, "rb") for p in img_paths] - # optional mask (only for the first image) - mask_file = None - if "mask_path" in kwargs and kwargs["mask_path"] is not None: - mask_file = open(kwargs["mask_path"], "rb") - # construct API args - edit_kwargs = { - "model": model, - "image": image_files if len(image_files) > 1 else image_files[0], - "prompt": prompt, - "n": n, - "size": kwargs.get("size"), - } - - if model.startswith("gpt-image-"): - edit_kwargs["quality"] = kwargs.get("quality", "auto") - - if mask_file: - edit_kwargs["mask"] = mask_file - callback = openai.images.edit - - res = openai.images.edit(**edit_kwargs) - # clean up file handles - for f in image_files: - f.close() - if mask_file: - mask_file.close() - else: - raise ValueError(f"Unknown image operation: {operation}") - - except Exception as e: - if except_remedy is None: - raise - res = except_remedy(self, e, callback, argument) - - # wrap it up - metadata = {} - result = GPTImageResult(res) - return [result], metadata diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/embedding/engine_llama_cpp.py b/symbolicai-main/symbolicai-main/symai/backend/engines/embedding/engine_llama_cpp.py deleted file mode 100644 index f8cfc5171cc61f5282d738a825a3708f6e4fe981..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/embedding/engine_llama_cpp.py +++ /dev/null @@ -1,134 +0,0 @@ -import asyncio -import logging -from multiprocessing import Value -from typing import Optional - -import aiohttp -import nest_asyncio -import numpy as np - -from ....core_ext import retry -from ....utils import CustomUserWarning -from ...base import Engine -from ...settings import SYMAI_CONFIG, SYMSERVER_CONFIG - -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - -class LlamaCppEmbeddingEngine(Engine): - _retry_params = { - 'tries': 5, - 'delay': 2, - 'max_delay': 60, - 'backoff': 2, - 'jitter': (1, 5), - 'graceful': True - } - _timeout_params = { - 'read': None, - 'connect': None, - } - - def __init__( - self, - retry_params: dict = _retry_params, - timeout_params: dict = _timeout_params - ): - super().__init__() - self.config = SYMAI_CONFIG - if self.id() != 'embedding': - return - if not SYMSERVER_CONFIG.get('online'): - CustomUserWarning('You are using the llama.cpp embedding engine, but the server endpoint is not started. Please start the server with `symserver [--args]`.', raise_with=ValueError) - - self.server_endpoint = f"http://{SYMSERVER_CONFIG.get('--host')}:{SYMSERVER_CONFIG.get('--port')}" - self.timeout_params = self._validate_timeout_params(timeout_params) - self.retry_params = self._validate_retry_params(retry_params) - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config.get('EMBEDDING_ENGINE_MODEL') and self.config.get('EMBEDDING_ENGINE_MODEL').startswith('llama'): - return 'embedding' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'EMBEDDING_ENGINE_MODEL' in kwargs: - self.model = kwargs['EMBEDDING_ENGINE_MODEL'] - - def _validate_timeout_params(self, timeout_params): - if not isinstance(timeout_params, dict): - raise ValueError("timeout_params must be a dictionary") - assert all(key in timeout_params for key in ['read', 'connect']), "Available keys: ['read', 'connect']" - return timeout_params - - def _validate_retry_params(self, retry_params): - if not isinstance(retry_params, dict): - raise ValueError("retry_params must be a dictionary") - assert all(key in retry_params for key in ['tries', 'delay', 'max_delay', 'backoff', 'jitter', 'graceful']), \ - "Available keys: ['tries', 'delay', 'max_delay', 'backoff', 'jitter', 'graceful']" - return retry_params - - @staticmethod - def _get_event_loop() -> asyncio.AbstractEventLoop: - """Gets or creates an event loop.""" - try: - current_loop = asyncio.get_event_loop() - if current_loop.is_closed(): - raise RuntimeError("Event loop is closed.") - return current_loop - except RuntimeError: - new_loop = asyncio.new_event_loop() - asyncio.set_event_loop(new_loop) - return new_loop - - async def _arequest(self, text: str) -> dict: - """Makes an async HTTP request to the llama.cpp server.""" - @retry(**self.retry_params) - async def _make_request(): - timeout = aiohttp.ClientTimeout( - sock_connect=self.timeout_params['connect'], - sock_read=self.timeout_params['read'] - ) - async with aiohttp.ClientSession(timeout=timeout) as session: - async with session.post( - f"{self.server_endpoint}/v1/embeddings", - json={"input": text} - ) as res: - if res.status != 200: - raise ValueError(f"Request failed with status code: {res.status}") - return await res.json() - - return await _make_request() - - def forward(self, argument): - prepared_input = argument.prop.prepared_input - kwargs = argument.kwargs - - inp = prepared_input if isinstance(prepared_input, list) else [prepared_input] - new_dim = kwargs.get('new_dim') - - nest_asyncio.apply() - loop = self._get_event_loop() - - try: - res = loop.run_until_complete(self._arequest(inp)) - except Exception as e: - raise ValueError(f"Request failed with error: {str(e)}") - - if new_dim: - raise NotImplementedError("new_dim is not yet supported") - - if res is not None: - output = [r["embedding"] for r in res["data"]] - else: - output = None - metadata = {'raw_output': res} - - return [output], metadata - - def prepare(self, argument): - assert not argument.prop.processed_input, "LlamaCppEmbeddingEngine does not support processed_input." - argument.prop.prepared_input = argument.prop.entries diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/embedding/engine_openai.py b/symbolicai-main/symbolicai-main/symai/backend/engines/embedding/engine_openai.py deleted file mode 100644 index 92d5bfe94434717053d91c78b7f4254aa8e68102..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/embedding/engine_openai.py +++ /dev/null @@ -1,84 +0,0 @@ -import logging -from typing import Optional - -import numpy as np -import openai - -from ...base import Engine -from ...mixin.openai import OpenAIMixin -from ...settings import SYMAI_CONFIG - -logging.getLogger("openai").setLevel(logging.ERROR) -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - - -class EmbeddingEngine(Engine, OpenAIMixin): - def __init__(self, api_key: Optional[str] = None, model: Optional[str] = None): - super().__init__() - logger = logging.getLogger('openai') - logger.setLevel(logging.WARNING) - self.config = SYMAI_CONFIG - if self.id() != 'embedding': - return # do not initialize if not embedding; avoids conflict with llama.cpp check in EngineRepository.register_from_package - openai.api_key = self.config['EMBEDDING_ENGINE_API_KEY'] if api_key is None else api_key - self.model = self.config['EMBEDDING_ENGINE_MODEL'] if model is None else model - self.max_tokens = self.api_max_context_tokens() - self.embedding_dim = self.api_embedding_dims() - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config.get('EMBEDDING_ENGINE_API_KEY') and self.config['EMBEDDING_ENGINE_MODEL'].startswith('text-embedding'): - return 'embedding' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'EMBEDDING_ENGINE_API_KEY' in kwargs: - openai.api_key = kwargs['EMBEDDING_ENGINE_API_KEY'] - if 'EMBEDDING_ENGINE_MODEL' in kwargs: - self.model = kwargs['EMBEDDING_ENGINE_MODEL'] - - def forward(self, argument): - prepared_input = argument.prop.prepared_input - args = argument.args - kwargs = argument.kwargs - - inp = prepared_input if isinstance(prepared_input, list) else [prepared_input] - except_remedy = kwargs.get('except_remedy') - new_dim = kwargs.get('new_dim') - - try: - res = openai.embeddings.create(model=self.model, input=inp) - except Exception as e: - if except_remedy is None: - raise e - callback = openai.embeddings.create - res = except_remedy(e, inp, callback, self, *args, **kwargs) - - if new_dim: - mn = min(new_dim, self.embedding_dim) #@NOTE: new_dim should be less than or equal to the original embedding dim - output = [self._normalize_l2(r.embedding[:mn]) for r in res.data] - else: - output = [r.embedding for r in res.data] - - metadata = {"raw_output": res} - - return [output], metadata - - def prepare(self, argument): - assert not argument.prop.processed_input, "EmbeddingEngine does not support processed_input." - argument.prop.prepared_input = argument.prop.entries - - def _normalize_l2(self, x): - x = np.array(x) - if x.ndim == 1: - norm = np.linalg.norm(x) - if norm == 0: - return x.tolist() - return (x / norm).tolist() - else: - norm = np.linalg.norm(x, 2, axis=1, keepdims=True) - return np.where(norm == 0, x, x / norm).tolist() diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/embedding/engine_plugin_embeddings.py b/symbolicai-main/symbolicai-main/symai/backend/engines/embedding/engine_plugin_embeddings.py deleted file mode 100644 index 54f16a2c36229b647bdd6ef45ab44daa5a4e77d5..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/embedding/engine_plugin_embeddings.py +++ /dev/null @@ -1,12 +0,0 @@ -from ...base import Engine -from ...settings import SYMAI_CONFIG - - -class PluginEmbeddingEngine(Engine): - def id(self) -> str: - if not SYMAI_CONFIG['EMBEDDING_ENGINE_API_KEY'] and not SYMAI_CONFIG['EMBEDDING_ENGINE_MODEL'].startswith("llama"): - from ....functional import EngineRepository - - # Register the embedding engine from the plugin - EngineRepository.register_from_plugin('embedding', plugin='ExtensityAI/embeddings', kwargs={'model': 'all-mpnet-base-v2'}, allow_engine_override=True) - return super().id() # do not register this engine as we want the plugin to be used diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/execute/engine_python.py b/symbolicai-main/symbolicai-main/symai/backend/engines/execute/engine_python.py deleted file mode 100644 index c8fff6f65758f6b9a100e97a733b320a54444699..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/execute/engine_python.py +++ /dev/null @@ -1,98 +0,0 @@ -from ....symbol import Result -from ...base import Engine - - -def full_stack(): - import sys - import traceback - exc = sys.exc_info()[0] - stack = traceback.extract_stack()[-10:-1] # last one would be full_stack() - if exc is not None: # i.e. an exception is present - del stack[-1] # remove call of full_stack, the printed exception - # will contain the caught exception caller instead - trc = 'Traceback (most recent call last):\n' - stackstr = trc + ''.join(traceback.format_list(stack)) - if exc is not None: - stackstr += ' ' + traceback.format_exc().lstrip(trc) - return stackstr - - -class PythonEngine(Engine): - """PythonEngine executes Python code dynamically while managing the code execution - context using provided global and local namespaces. This engine encapsulates the - execution process, handling both successful execution and exception scenarios. - - Usage: - - Instantiate the PythonEngine. - - Call the forward method with the desired Python code and context variables. - - The forward method expects a 'prompt' containing the executable code and can also - accept 'globals', 'locals', 'input_handler', 'output_handler', and 'metadata' as keyword - arguments to manage the execution context and handle input/output operations. - - The Python code should contain a 'run' function which serves as the entry point. The - run function can accept any arguments (*args, **kwargs) and return any type of value. - The code execution result is encapsulated in 'res', which is then managed by the - local or global namespace. - - Parameters: - *args: Variable length argument list. - **kwargs: Arbitrary keyword arguments containing 'prompt' and context variables. - - Returns: - A list containing the results of the code execution within a context dict and a - metadata dict capturing execution details. - - Example: - - engine = PythonEngine() - code = ''' - def run(*args, **kwargs): - return "Hello, " + args[0] - res = run(value) - ''' - results, metadata = engine.forward(prompt=code, globals={}, locals={}, value='World') - - Note: - The 'run' function must be defined, and its execution result must be assigned to 'res'. - In case of an exception, the engine will provide a full traceback to help with debugging. - """ - - def __init__(self): - super().__init__() - self.name = self.__class__.__name__ - - def id(self) -> str: - return 'execute' - - def forward(self, argument): - code = argument.prop.prepared_input - kwargs = argument.kwargs - globals_ = kwargs['globals'] if 'globals' in kwargs else {} - locals_ = kwargs['locals'] if 'locals' in kwargs else {} - input_handler = kwargs['input_handler'] if 'input_handler' in kwargs else None - if input_handler: - input_handler((code,)) - - rsp = None - err = None - try: - exec(str(code), globals_, locals_) - rsp = {'globals': globals_, 'locals': locals_} - if 'res' in locals_: - rsp['locals_res'] = locals_['res'] - if 'res' in globals_: - rsp['globals_res'] = globals_['res'] - rsp = Result(rsp) - except Exception as e: - err = e - raise e - - metadata = {} - metadata['error'] = None if not err else full_stack() - - return [rsp], metadata - - def prepare(self, argument): - assert not argument.prop.processed_input, "PythonEngine does not support processed_input." - argument.prop.prepared_input = str(argument.prop.instance) diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/files/engine_io.py b/symbolicai-main/symbolicai-main/symai/backend/engines/files/engine_io.py deleted file mode 100644 index 1fe7e7002a6fb52179be16afc4a54669a28562ce..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/files/engine_io.py +++ /dev/null @@ -1,178 +0,0 @@ -import logging -import os -from dataclasses import dataclass -from pathlib import Path - -import pypdf -import tika -from tika import unpack - -from ...base import Engine - -# initialize tika server -tika.initVM() -# suppress tika logging -logging.getLogger('tika').setLevel(logging.CRITICAL) - - -@dataclass -class TextContainer: - id: str - page: str - text: str - - -class FileEngine(Engine): - def __init__(self): - super().__init__() - self.name = self.__class__.__name__ - - def id(self) -> str: - return 'files' - - def _read_slice_file(self, file_path, argument): - # check if file is empty - with_metadata = argument.kwargs.get('with_metadata', False) - id = Path(argument.prop.prepared_input).stem.replace(' ', '_') - if file_path is None or file_path.strip() == '': - return None - - # check if file slice is used - slices_ = None - if '[' in file_path and ']' in file_path: - file_parts = file_path.split('[') - file_path = file_parts[0] - # remove string up to '[' and after ']' - slices_s = file_parts[1].split(']')[0].split(',') - slices_ = [] - for s in slices_s: - if s == '': - continue - elif ':' in s: - s_split = s.split(':') - if len(s_split) == 2: - start_slice = int(s_split[0]) if s_split[0] != '' else None - end_slice = int(s_split[1]) if s_split[1] != '' else None - slices_.append(slice(start_slice, end_slice, None)) - elif len(s_split) == 3: - start_slice = int(s_split[0]) if s_split[0] != '' else None - end_slice = int(s_split[1]) if s_split[1] != '' else None - step_slice = int(s_split[2]) if s_split[2] != '' else None - slices_.append(slice(start_slice, end_slice, step_slice)) - else: - slices_.append(int(s)) - - # check if file exists - assert os.path.exists(file_path), f'File does not exist: {file_path}' - - # verify if file is empty - if os.path.getsize(file_path) <= 0: - return '' - - file_ = unpack.from_file(str(file_path)) - if 'content' in file_: - content = file_['content'] - else: - content = str(file_) - - if content is None: - return None - content = content.split('\n') - - if slices_ is not None: - new_content = [] - for s in slices_: - new_content.extend(content[s]) - content = new_content - content = '\n'.join(content) - content = content.encode('utf8', 'ignore').decode('utf8', 'ignore') - return content if not with_metadata else [TextContainer(id, None, content)] - - - def reset_eof_of_pdf_return_stream(self, pdf_stream_in: list): - actual_line = len(pdf_stream_in) # Predefined value in case EOF not found - # find the line position of the EOF - for i, x in enumerate(pdf_stream_in[::-1]): - if b'%%EOF' in x: - actual_line = len(pdf_stream_in)-i - print(f'EOF found at line position {-i} = actual {actual_line}, with value {x}') - break - - # return the list up to that point - return pdf_stream_in[:actual_line] - - def fix_pdf(self, file_path: str): - # opens the file for reading - with open(file_path, 'rb') as p: - txt = (p.readlines()) - - # get the new list terminating correctly - txtx = self.reset_eof_of_pdf_return_stream(txt) - - # write to new pdf - new_file_path = f'{file_path}_fixed.pdf' - with open(new_file_path, 'wb') as f: - f.writelines(txtx) - - fixed_pdf = pypdf.PdfReader(new_file_path) - return fixed_pdf - - def read_text(self, pdf_reader, page_range, argument): - txt = [] - n_pages = len(pdf_reader.pages) - with_metadata = argument.kwargs.get('with_metadata', False) - id = Path(argument.prop.prepared_input).stem.replace(' ', '_') - for i in range(n_pages)[slice(0, n_pages) if page_range is None else page_range]: - page = pdf_reader.pages[i] - extracted = page.extract_text() - extracted = extracted.encode('utf8', 'ignore').decode('utf8', 'ignore') - if with_metadata: - txt.append(TextContainer(id, str(i), extracted)) - else: - txt.append(extracted) - - return '\n'.join(txt) if not with_metadata else txt - - def forward(self, argument): - kwargs = argument.kwargs - path = argument.prop.prepared_input - - if '.pdf' in path: - page_range = None - if 'slice' in kwargs: - page_range = kwargs['slice'] - if isinstance(page_range, tuple) or isinstance(page_range, list): - page_range = slice(*page_range) - - rsp = '' - try: - with open(str(path), 'rb') as f: - # creating a pdf reader object - pdf_reader = pypdf.PdfReader(f) - rsp = self.read_text(pdf_reader, page_range, argument) - except Exception as e: - print(f'Error reading PDF: {e} | {path}') - if 'fix_pdf' not in kwargs or not kwargs['fix_pdf']: - raise e - fixed_pdf = self.fix_pdf(str(path)) - pdf_reader_fixed = pypdf.PdfReader(fixed_pdf) - rsp = self.read_text(pdf_reader_fixed, page_range, argument) - else: - try: - rsp = self._read_slice_file(path, argument) - except Exception as e: - print(f'Error reading empty file: {e} | {path}') - raise e - - if rsp is None: - raise Exception(f'Error reading file - empty result: {path}') - - metadata = {} - - return [rsp], metadata - - def prepare(self, argument): - assert not argument.prop.processed_input, "FileEngine does not support processed_input." - path = argument.prop.path - path = path.replace('\\', '') - argument.prop.prepared_input = path diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/imagecaptioning/engine_blip2.py b/symbolicai-main/symbolicai-main/symai/backend/engines/imagecaptioning/engine_blip2.py deleted file mode 100644 index e60378248f76150afbb2e06967fb3c750d548e7c..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/imagecaptioning/engine_blip2.py +++ /dev/null @@ -1,78 +0,0 @@ -from typing import List - -import requests -import torch - -try: - from lavis.models import load_model_and_preprocess -except ImportError: - load_model_and_preprocess = None - -from PIL import Image - -from ...base import Engine -from ...settings import SYMAI_CONFIG - - -class Blip2Engine(Engine): - def __init__(self): - super().__init__() - self.config = SYMAI_CONFIG - ids = self.config['CAPTION_ENGINE_MODEL'].split('/') - if len(ids) != 2: - # return unregistered engine - return - self.name_id = ids[0] - self.model_id = ids[1] - self.model = None # lazy loading - self.vis_processors = None # lazy loading - self.txt_processors = None # lazy loading - self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config['CAPTION_ENGINE_MODEL'] and \ - 'blip2' in self.config['CAPTION_ENGINE_MODEL']: - return 'imagecaptioning' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'CAPTION_ENGINE_MODEL' in kwargs: - self.model_id = kwargs['CAPTION_ENGINE_MODEL'] - - def forward(self, argument): - if load_model_and_preprocess is None: - raise ImportError('Blip2 is not installed. Please install it with `pip install symbolicai[blip2]`') - if self.model is None: - self.model, self.vis_processors, self.txt_processors = load_model_and_preprocess(name = self.name_id, - model_type = self.model_id, - is_eval = True, - device = self.device) - - image, prompt = argument.prop.prepared_input - kwargs = argument.kwargs - except_remedy = kwargs['except_remedy'] if 'except_remedy' in kwargs else None - - if 'http' in image: - image = Image.open(requests.get(image, stream=True).raw).convert('RGB') - elif '/' in image or '\\' in image: - image = Image.open(image).convert('RGB') - - try: - image = self.vis_processors['eval'](image).unsqueeze(0).to(self.device) - prompt = self.txt_processors['eval'](prompt) - res = self.model.generate(samples={"image": image, "prompt": prompt}, use_nucleus_sampling=True, num_captions=3) - except Exception as e: - if except_remedy is None: - raise e - callback = self.model.generate - res = except_remedy(self, e, callback, argument) - - metadata = {} - - return [res], metadata - - def prepare(self, argument): - assert not argument.prop.processed_input, "Blip2Engine does not support processed_input." - argument.prop.prepared_input = (argument.prop.image, argument.prop.prompt) diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/imagecaptioning/engine_llavacpp_client.py b/symbolicai-main/symbolicai-main/symai/backend/engines/imagecaptioning/engine_llavacpp_client.py deleted file mode 100644 index 33836df859531417a8db3378fa10d6f5d173498f..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/imagecaptioning/engine_llavacpp_client.py +++ /dev/null @@ -1,165 +0,0 @@ -import logging -import requests -import json -import io - -from typing import List -from requests_toolbelt.multipart.encoder import MultipartEncoder -from PIL.Image import Image - -from ...base import Engine -from ...settings import SYMAI_CONFIG -from ....symbol import Result - - -def image_to_byte_array(image: Image, format='PNG') -> bytes: - # BytesIO is a file-like buffer stored in memory - imgByteArr = io.BytesIO() - # image.save expects a file-like as a argument - image.save(imgByteArr, format=format) - # Turn the BytesIO object back into a bytes object - imgByteArr = imgByteArr.getvalue() - return imgByteArr - - -class LLaMAResult(Result): - def __init__(self, value=None, *args, **kwargs): - super().__init__(value, *args, **kwargs) - self._value = value - self.error = None - self.raw = value - self._perse_result() - - def _perse_result(self): - val = json.loads(self.value) - self.value = val - if 'error' in val: - self.error = val['error'] - if 'content' in val: - self.value = val['content'] - - -class LLaMACppClientEngine(Engine): - def __init__(self, host: str = 'localhost', port: int = 8080, timeout: int = 240): - super().__init__() - logger = logging.getLogger('nesy_client') - logger.setLevel(logging.WARNING) - self.config = SYMAI_CONFIG - self.host = host - self.port = port - self.timeout = timeout - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config['CAPTION_ENGINE_MODEL'] and \ - 'llavacpp' in self.config['CAPTION_ENGINE_MODEL']: - return 'imagecaptioning' - return super().id() # default to unregistered - - @property - def max_tokens(self): - return 4096 - - def forward(self, argument): - prompts = argument.prop.prepared_input - kwargs = argument.kwargs - system, user, image = prompts - # escape special characters - system = system['content'] - user = user['content'] - - if isinstance(image['content'], Image): - # format image to bytes - format_ = argument.prop.image_format if argument.prop.image_format else 'PNG' - im_bytes = image_to_byte_array(image['content'], format=format_) - else: - # Convert image to bytes, open as binary - with open(image['content'], 'rb') as f: - im_bytes = f.read() - # Create multipart/form-data payload - payload = MultipartEncoder( - fields={ - 'user_prompt': ('user_prompt', user, 'text/plain'), - 'image_file': ('image_file', im_bytes, 'application/octet-stream'), - 'system_prompt': ('system_prompt', system, 'text/plain') - } - ) - # Update the headers for multipart/form-data - headers = {'Content-Type': payload.content_type} - api = f'http://{self.host}:{self.port}/llava' - except_remedy = kwargs['except_remedy'] if 'except_remedy' in kwargs else None - try: - # use http localhost 8000 to send a request to the server - rsp = requests.post(api, data=payload, headers=headers, timeout=self.timeout) - res = rsp.text - except Exception as e: - if except_remedy is None: - raise e - callback = lambda: requests.post(api, data=payload, headers=headers, timeout=self.timeout) - res = except_remedy(self, e, callback, argument) - - metadata = {} - - res = LLaMAResult(res) - rsp = [res] - output = rsp if isinstance(prompts, list) else rsp[0] - return output, metadata - - def prepare(self, argument): - if argument.prop.raw_input: - if not argument.prop.processed_input: - raise ValueError('Need to provide a prompt instruction to the engine if raw_input is enabled.') - argument.prop.prepared_input = argument.prop.processed_input - return - - user: str = "" - system: str = "" - system = f'{system}\n' if system and len(system) > 0 else '' - - ref = argument.prop.instance - static_ctxt, dyn_ctxt = ref.global_context - if len(static_ctxt) > 0: - system += f"[STATIC CONTEXT]\n{static_ctxt}\n\n" - - if len(dyn_ctxt) > 0: - system += f"[DYNAMIC CONTEXT]\n{dyn_ctxt}\n\n" - - payload = argument.prop.payload - if argument.prop.payload: - system += f"[ADDITIONAL CONTEXT]\n{str(payload)}\n\n" - - examples: List[str] = argument.prop.examples - if examples and len(examples) > 0: - system += f"[EXAMPLES]\n{str(examples)}\n\n" - - if argument.prop.prompt is not None and len(argument.prop.prompt) > 0: - val = str(argument.prop.prompt) - # in this engine, instructions are considered as user prompts - user += f"[INSTRUCTION]\n{val}" - - suffix: str = str(argument.prop.processed_input) - - if '[SYSTEM_INSTRUCTION::]: <<<' in suffix and argument.prop.parse_system_instructions: - parts = suffix.split('\n>>>\n') - # first parts are the system instructions - c = 0 - for i, p in enumerate(parts): - if 'SYSTEM_INSTRUCTION' in p: - system += f"{p}\n" - c += 1 - else: - break - # last part is the user input - suffix = '\n>>>\n'.join(parts[c:]) - user += f"{suffix}" - - if argument.prop.template_suffix: - user += f"\n[[PLACEHOLDER]]\n{str(argument.prop.template_suffix)}\n\n" - user += f"Only generate content for the placeholder `[[PLACEHOLDER]]` following the instructions and context information. Do NOT write `[[PLACEHOLDER]]` or anything else in your output.\n\n" - - user_prompt = { "role": "user", "content": user } - argument.prop.prepared_input = [ - { "role": "system", "content": system }, - user_prompt, - { "role": "image", "content": argument.prop.image } - ] diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/index/engine_pinecone.py b/symbolicai-main/symbolicai-main/symai/backend/engines/index/engine_pinecone.py deleted file mode 100644 index 5c3f149a348c3d3eafe51ce2b87227efc3ae463d..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/index/engine_pinecone.py +++ /dev/null @@ -1,234 +0,0 @@ -import itertools -import warnings -import numpy as np - -warnings.filterwarnings('ignore', module='pinecone') -try: - from pinecone import Pinecone, ServerlessSpec -except: - pass - -from ...base import Engine -from ...settings import SYMAI_CONFIG -from .... import core_ext -from ....symbol import Result - - -def chunks(iterable, batch_size=100): - """A helper function to break an iterable into chunks of size batch_size.""" - it = iter(iterable) - chunk = list(itertools.islice(it, batch_size)) - while chunk: - yield chunk - chunk = list(itertools.islice(it, batch_size)) - - -class PineconeResult(Result): - def __init__(self, res, query: str, embedding: list, **kwargs): - super().__init__(res, **kwargs) - self.raw = res - self._query = query - self._value = self._process(res) - self._metadata.raw = embedding - - def _process(self, res): - if not res: - return None - try: - res = self._to_symbol(res).ast() - except Exception as e: - message = ['Sorry, failed to interact with index. Please check index name and try again later:', str(e)] - # package the message for the IndexResult class - res = {'matches': [{'metadata': {'text': '\n'.join(message)}}]} - return [v['metadata']['text'] for v in res['matches']] - - def _unpack_matches(self): - if not self.value: - return - - for i, match in enumerate(self.value): - match = match.strip() - if match.startswith('# ----[FILE_START]') and '# ----[FILE_END]' in match: - m = match.split('[FILE_CONTENT]:')[-1].strip() - splits = m.split('# ----[FILE_END]') - assert len(splits) >= 2, 'Invalid file format: {}'.format(splits) - content = splits[0] - file_name = ','.join(splits[1:]) # TODO: check why there are multiple file names - yield file_name.strip(), content.strip() - else: - yield i+1, match - - def __str__(self): - str_view = '' - for filename, content in self._unpack_matches(): - # indent each line of the content - content = '\n'.join([' ' + line for line in content.split('\n')]) - str_view += f'* {filename}\n{content}\n\n' - return f''' -[RESULT] -{'-=-' * 13} - -Query: {self._query} - -{'-=-' * 13} - -Matches: - -{str_view} -{'-=-' * 13} -''' - - def _repr_html_(self) -> str: - # return a nicely styled HTML list results based on retrieved documents - doc_str = '' - for filename, content in self._unpack_matches(): - doc_str += f'
  • {filename}
    {content}
  • \n' - return f'
      {doc_str}
    ' - - -class PineconeIndexEngine(Engine): - _default_api_key = SYMAI_CONFIG['INDEXING_ENGINE_API_KEY'] - _default_environment = SYMAI_CONFIG['INDEXING_ENGINE_ENVIRONMENT'] - _default_index_name = 'dataindex' - _default_index_dims = 1536 - _default_index_top_k = 5 - _default_index_metric = 'cosine' - _default_index_values = True - _default_index_metadata = True - _default_retry_tries = 20 - _default_retry_delay = 0.5 - _default_retry_max_delay = -1 - _default_retry_backoff = 1 - _default_retry_jitter = 0 - - def __init__( - self, - api_key=_default_api_key, - environment=_default_environment, - index_name=_default_index_name, - index_dims=_default_index_dims, - index_top_k=_default_index_top_k, - index_metric=_default_index_metric, - index_values=_default_index_values, - index_metadata=_default_index_metadata, - tries=_default_retry_tries, - delay=_default_retry_delay, - max_delay=_default_retry_max_delay, - backoff=_default_retry_backoff, - jitter=_default_retry_jitter, - ): - super().__init__() - self.index_name = index_name - self.index_dims = index_dims - self.index_top_k = index_top_k - self.index_values = index_values - self.index_metadata = index_metadata - self.index_metric = index_metric - self.api_key = api_key - self.environment = environment - self.tries = tries - self.delay = delay - self.max_delay = max_delay - self.backoff = backoff - self.jitter = jitter - self.index = None - self.pinecone = None - self.name = self.__class__.__name__ - - def id(self) -> str: - if SYMAI_CONFIG['INDEXING_ENGINE_API_KEY']: - if Pinecone is None: - print('Pinecone is not installed. Please install it with `pip install symbolicai[pinecone]`.') - return 'index' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'INDEXING_ENGINE_API_KEY' in kwargs: - self.api_key = kwargs['INDEXING_ENGINE_API_KEY'] - if 'INDEXING_ENGINE_ENVIRONMENT' in kwargs: - self.environment = kwargs['INDEXING_ENGINE_ENVIRONMENT'] - - def _configure_index(self, **kwargs): - index_name = kwargs['index_name'] if 'index_name' in kwargs else self.index_name - - del_ = kwargs['index_del'] if 'index_del' in kwargs else False - if self.index is not None and del_: - self.pinecone.delete_index(index_name) - - get_ = kwargs['index_get'] if 'index_get' in kwargs else False - if self.index is not None and get_: - self.index = self.pinecone.Index(name=index_name) - - def forward(self, argument): - assert self.api_key, 'Please set the API key for Pinecone indexing engine.' - assert self.environment, 'Please set the environment for Pinecone indexing engine.' - assert self.index_name, 'Please set the index name for Pinecone indexing engine.' - - kwargs = argument.kwargs - embedding = argument.prop.prepared_input - query = argument.prop.ori_query - operation = argument.prop.operation - index_name = argument.prop.index_name if argument.prop.index_name else self.index_name - index_dims = argument.prop.index_dims if argument.prop.index_dims else self.index_dims - rsp = None - - if self.index is None: - self._init_index_engine(index_name=index_name, index_dims=index_dims, index_metric=self.index_metric) - - if index_name != self.index_name: - assert index_name, 'Please set a valid index name for Pinecone indexing engine.' - # switch index - self.index_name = index_name - kwargs['index_get'] = True - self._configure_index(**kwargs) - - if operation == 'search': - index_top_k = kwargs['index_top_k'] if 'index_top_k' in kwargs else self.index_top_k - index_values = kwargs['index_values'] if 'index_values' in kwargs else self.index_values - index_metadata = kwargs['index_metadata'] if 'index_metadata' in kwargs else self.index_metadata - rsp = self._query(embedding, index_top_k, index_values, index_metadata) - - elif operation == 'add': - for ids_vectors_chunk in chunks(embedding, batch_size=100): - self._upsert(ids_vectors_chunk) - - elif operation == 'config': - self._configure_index(**kwargs) - - else: - raise ValueError('Invalid operation') - - metadata = {} - - rsp = PineconeResult(rsp, query, embedding) - return [rsp], metadata - - def prepare(self, argument): - assert not argument.prop.processed_input, 'Pinecone indexing engine does not support processed_input.' - argument.prop.prepared_input = argument.prop.prompt - - def _init_index_engine(self, index_name, index_dims, index_metric): - self.pinecone = Pinecone(api_key=self.api_key) - - if index_name is not None and index_name not in str(self.pinecone.list_indexes()): - self.pinecone.create_index(name=index_name, dimension=index_dims, metric=index_metric, spec=ServerlessSpec( - cloud='aws', - region=self.environment - )) - - self.index = self.pinecone.Index(name=index_name) - - def _upsert(self, vectors): - @core_ext.retry(tries=self.tries, delay=self.delay, max_delay=self.max_delay, backoff=self.backoff, jitter=self.jitter) - def _func(): - return self.index.upsert(vectors=vectors) - - return _func() - - def _query(self, query, index_top_k, index_values, index_metadata): - @core_ext.retry(tries=self.tries, delay=self.delay, max_delay=self.max_delay, backoff=self.backoff, jitter=self.jitter) - def _func(): - return self.index.query(vector=query, top_k=index_top_k, include_values=index_values, include_metadata=index_metadata) - - return _func() diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/index/engine_vectordb.py b/symbolicai-main/symbolicai-main/symai/backend/engines/index/engine_vectordb.py deleted file mode 100644 index 7201a20e41dc2457b6ee9bdeac21efce66dfd53f..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/index/engine_vectordb.py +++ /dev/null @@ -1,205 +0,0 @@ -import itertools - -from ....extended.vectordb import VectorDB -from ....symbol import Result -from ...base import Engine -from ...settings import SYMAI_CONFIG - - -def chunks(iterable, batch_size=100): - """A helper function to break an iterable into chunks of size batch_size.""" - it = iter(iterable) - chunk = list(itertools.islice(it, batch_size)) - while chunk: - yield chunk - chunk = list(itertools.islice(it, batch_size)) - - -class VectorDBResult(Result): - def __init__(self, res, query: str, embedding: list, **kwargs): - super().__init__(res, **kwargs) - self.raw = res - self._query = query - self._value = self._process(res) - self._metadata.raw = embedding - - def _process(self, res): - if not res: - return None - try: - res = self._to_symbol(res).ast() - except Exception as e: - message = ['Sorry, failed to interact with index. Please check index name and try again later:', str(e)] - # package the message for the IndexResult class - res = {'matches': [{'metadata': {'text': '\n'.join(message)}}]} - return [v['metadata']['text'] for v in res] - - def _unpack_matches(self): - if not self.value: - return - - for i, match in enumerate(self.value): - match = match.strip() - if match.startswith('# ----[FILE_START]') and '# ----[FILE_END]' in match: - m = match.split('[FILE_CONTENT]:')[-1].strip() - splits = m.split('# ----[FILE_END]') - assert len(splits) >= 2, 'Invalid file format: {}'.format(splits) - content = splits[0] - file_name = ','.join(splits[1:]) # TODO: check why there are multiple file names - yield file_name.strip(), content.strip() - else: - yield i+1, match - - def __str__(self): - str_view = '' - for filename, content in self._unpack_matches(): - # indent each line of the content - content = '\n'.join([' ' + line for line in content.split('\n')]) - str_view += f'* {filename}\n{content}\n\n' - return f''' -[RESULT] -{'-=-' * 13} - -Query: {self._query} - -{'-=-' * 13} - -Matches: - -{str_view} -{'-=-' * 13} -''' - - def _repr_html_(self) -> str: - # return a nicely styled HTML list results based on retrieved documents - doc_str = '' - for filename, content in self._unpack_matches(): - doc_str += f'
  • {filename}
    {content}
  • \n' - return f'
      {doc_str}
    ' - - -class VectorDBIndexEngine(Engine): - # Updated default values to be congruent with VectorDB's defaults - _default_index_name = 'dataindex' - _default_index_dims = 768 - _default_index_top_k = 5 - _default_index_metric = 'cosine' - _index_dict = {} - _index_storage_file = None - - def __init__( - self, - index_name=_default_index_name, - index_dims=_default_index_dims, - index_top_k=_default_index_top_k, - index_metric=_default_index_metric, - index_dict=_index_dict, - index_storage_file=_index_storage_file, - **kwargs - ): - super().__init__() - self.index_name = index_name - self.index_dims = index_dims - self.index_top_k = index_top_k - self.index_metric = index_metric - self.storage_file = index_storage_file - self.model = None - # Initialize an instance of VectorDB - # Note that embedding_function and vectors are not passed as VectorDB will compute it on the fly - self.index = index_dict - self.name = self.__class__.__name__ - - def id(self) -> str: - if not SYMAI_CONFIG['INDEXING_ENGINE_API_KEY'] or SYMAI_CONFIG['INDEXING_ENGINE_API_KEY'] == '': - return 'index' - return super().id() # default to unregistered - - def forward(self, argument): - embedding = argument.prop.prepared_input - query = argument.prop.ori_query - operation = argument.prop.operation - index_name = argument.prop.index_name or self.index_name - index_dims = argument.prop.index_dims or self.index_dims - top_k = argument.prop.top_k or self.index_top_k - metric = argument.prop.metric or self.index_metric - similarities = argument.prop.similarities or False - storage_file = argument.prop.storage_file or self.storage_file - kwargs = argument.kwargs - rsp = None - - self._init(index_name, top_k, index_dims, metric) - - # Process each operation - if operation == 'search': - # Get the query text from the prepared input - query_vector = embedding[0] - # Perform search in the VectorDB - results = self.index[index_name](vector=query_vector, top_k=top_k, return_similarities=similarities) - rsp = [{'metadata': {'text': result}} for result in results] - - elif operation == 'add': - # Add provided documents (and optionally vectors) to the VectorDB - documents = [] - vectors = [] - for uid, vector, document in embedding: - vectors.append(vector) - documents.append(document['text']) - self.index[index_name].add(documents=documents, vectors=vectors) - - elif operation == 'config': - # Handle any configurations if needed (not applicable for in-memory VectorDB) - assert kwargs, 'Please provide a configuration by passing the appropriate kwargs. Currently, only `load`, `save`, `purge`.' - # Check if the index is to be persisted or loaded - if kwargs.get('load'): - assert storage_file, 'Please provide a `storage_file` path to load the pre-computed index.' - self.load(index_name, storage_file, index_dims, top_k, metric) - elif kwargs.get('save'): - # Save the pre-computed index to the provided path - self.save(index_name, storage_file) - elif kwargs.get('purge'): - # Purge the pre-computed index from the database path - self.purge(index_name) - else: - raise ValueError('Invalid configuration; please use either "load" or "save".') - else: - raise ValueError('Invalid operation; please use either "search", "add", or "config".') - - metadata = {} - - rsp = VectorDBResult(rsp, query, None) - return [rsp], metadata - - def _init(self, index_name, top_k, index_dims, metric, embedding_model=not None): - # Initialize the VectorDB if not already initialized - if index_name not in self.index: - self.index[index_name] = VectorDB( - index_name=index_name, - index_dims=index_dims, - top_k=top_k, - similarity_metric=metric, - embedding_model=embedding_model #@NOTE: the VectorDBIndexEngine class uses precomputed embeddings so the model is not needed in the VectorDB class - ) - - def prepare(self, argument): - assert not argument.prop.processed_input, 'VectorDB indexing engine does not support processed_input.' - argument.prop.prepared_input = argument.prop.prompt - - def load(self, index_name, storage_file, index_dims, top_k, metric): - self.index[index_name] = VectorDB( - index_dims=index_dims, - top_k=top_k, - similarity_metric=metric, - load_on_init=storage_file, - index_name=index_name - ) - - def save(self, index_name = None, storage_file = None): - index_name = index_name or self.index_name - storage_file = storage_file or self._index_storage_file - # Save the pre-computed index to the provided path - self.index[index_name].save(storage_file) - - def purge(self, index_name = None): - index_name = index_name or self.index_name - # Purge the pre-computed index from the database path - self.index[index_name].purge(index_name) diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/lean/engine_lean4.py b/symbolicai-main/symbolicai-main/symai/backend/engines/lean/engine_lean4.py deleted file mode 100644 index ba4cbe97f0dc7cdba55a89f2a8decc3cd6072c55..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/lean/engine_lean4.py +++ /dev/null @@ -1,234 +0,0 @@ -import os -import subprocess -import docker -import paramiko -import tempfile -from typing import Any, List, Tuple, Optional, Dict -from ...base import Engine -from ....symbol import Result - -class LeanResult(Result): - """ - Represents the result of executing a Lean code snippet. - - Attributes: - _value (Dict[str, str]): A dictionary containing the output of the Lean execution. - """ - def __init__(self, value: Dict[str, str]) -> None: - """ - Initializes a new LeanResult instance. - - Args: - value (Dict[str, str]): The result output of the Lean code execution. - """ - super().__init__(value) - self._value = value - -class LeanEngine(Engine): - """ - Engine for executing Lean code within a Docker container, providing SSH access for execution. - - Attributes: - ssh_host (str): The SSH host, defaulting to 'localhost'. - ssh_port (int): The SSH port, defaulting to 2222. - ssh_user (str): The SSH username, defaulting to 'root'. - ssh_key_path (str): The path to the SSH private key, defaulting to '~/.ssh/id_rsa'. - docker_client (docker.DockerClient): The Docker client used to manage containers. - container (docker.models.containers.Container): The Docker container used for executing Lean code. - """ - - def __init__( - self, - ssh_host: str = 'localhost', - ssh_port: int = 2222, - ssh_user: str = 'root', - ssh_key_path: str = '~/.ssh/id_rsa' - ) -> None: - """ - Initializes the LeanEngine with SSH and Docker configurations. - - Args: - ssh_host (str): The SSH host, defaulting to 'localhost'. - ssh_port (int): The SSH port, defaulting to 2222. - ssh_user (str): The SSH username, defaulting to 'root'. - ssh_key_path (str): The path to the SSH private key, defaulting to '~/.ssh/id_rsa'. - """ - super().__init__() - self.ssh_host: str = ssh_host - self.ssh_port: int = ssh_port - self.ssh_user: str = ssh_user - self.ssh_key_path: str = os.path.expanduser(ssh_key_path) - self.docker_client: docker.DockerClient = docker.from_env() - self.container: docker.models.containers.Container = self._ensure_container() - self.name = self.__class__.__name__ - self._setup_ssh() - - def id(self) -> str: - """ - Returns the identifier for the engine. - - Returns: - str: The identifier of the LeanEngine, 'lean4'. - """ - return 'lean4' - - def _ensure_container(self) -> docker.models.containers.Container: - """ - Ensures the Docker container for Lean execution exists, creating it if necessary. - - Returns: - docker.models.containers.Container: The Docker container instance used for Lean code execution. - """ - container_name: str = "lean-container" - - try: - existing_container: docker.models.containers.Container = self.docker_client.containers.get(container_name) - existing_container.remove(force=True) - except docker.errors.NotFound: - print(f"No existing container named '{container_name}' found. Proceeding to create a new one.") - - dockerfile: str = """ - FROM buildpack-deps:buster - - ENV ELAN_HOME=/usr/local/elan \ - PATH=/usr/local/elan/bin:$PATH \ - LEAN_VERSION=leanprover/lean4:nightly - - RUN apt-get update && apt-get install -y openssh-server curl && rm -rf /var/lib/apt/lists/* - - RUN curl https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -sSf | sh -s -- -y --default-toolchain $LEAN_VERSION; \ - elan default $LEAN_VERSION; \ - elan --version; \ - lean --version; \ - leanc --version; \ - lake --version; - - RUN mkdir /var/run/sshd && echo 'root:root' | chpasswd && sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config - - EXPOSE 22 - CMD ["/usr/sbin/sshd", "-D"] - """ - with tempfile.NamedTemporaryFile("w", delete=False) as temp_dockerfile: - temp_dockerfile.write(dockerfile) - dockerfile_path: str = temp_dockerfile.name - - image: docker.models.images.Image - image, _ = self.docker_client.images.build(path=os.path.dirname(dockerfile_path), dockerfile=dockerfile_path, tag="lean4-container-image") - os.remove(dockerfile_path) - - container: docker.models.containers.Container = self.docker_client.containers.run( - image.id, - detach=True, - name=container_name, - ports={'22/tcp': self.ssh_port} - ) - return container - - def _setup_ssh(self) -> None: - """ - Sets up SSH access to the Docker container, including generating an SSH key pair if necessary, - and configuring the container to accept SSH connections using the generated key. - """ - if not os.path.exists(self.ssh_key_path): - subprocess.run(['ssh-keygen', '-t', 'rsa', '-b', '2048', '-f', self.ssh_key_path, '-N', ''], check=True) - - subprocess.run(['docker', 'exec', self.container.id, 'mkdir', '-p', '/root/.ssh'], check=True) - subprocess.run(['docker', 'cp', f'{self.ssh_key_path}.pub', f'{self.container.id}:/root/.ssh/authorized_keys'], check=True) - subprocess.run(['docker', 'exec', self.container.id, 'chmod', '600', '/root/.ssh/authorized_keys'], check=True) - subprocess.run(['docker', 'exec', self.container.id, 'chown', 'root:root', '/root/.ssh/authorized_keys'], check=True) - - def forward(self, argument: Any) -> Tuple[List[LeanResult], dict]: - """ - Executes Lean code provided as a string or as an object property. - - Args: - argument (Any): The Lean code to be executed, either as a string or wrapped in an object. - - Returns: - Tuple[List[LeanResult], dict]: A tuple containing the result of the Lean execution and associated metadata. - """ - code: str = argument if isinstance(argument, str) else argument.prop.prepared_input - - rsp: Optional[LeanResult] = None - err: Optional[str] = None - tmpfile_path: Optional[str] = None - metadata: Dict[str, Any] = {} - try: - with tempfile.NamedTemporaryFile(delete=False, suffix=".lean") as tmpfile: - tmpfile.write(code.encode()) - tmpfile_path = tmpfile.name - - output, exec_metadata = self._execute_lean(tmpfile_path) - metadata.update(exec_metadata) - - if output: - rsp = LeanResult({'output': output}) - else: - metadata['status'] = 'no_output' - except Exception as e: - err = str(e) - metadata.update({'status': 'error', 'message': err}) - print(f"Error during Lean execution: {err}") - finally: - if tmpfile_path and os.path.exists(tmpfile_path): - os.remove(tmpfile_path) - if self.container: - print(f"Killing Docker container '{self.container.id}'...") - self.container.remove(force=True) - - return [rsp] if rsp else [], metadata - - def _execute_lean(self, filepath: str) -> Tuple[str, dict]: - """ - Executes a Lean script within the Docker container via SSH. - - Args: - filepath (str): The path to the Lean file to be executed. - - Returns: - Tuple[str, dict]: The output from the Lean execution and associated status metadata. - """ - try: - ssh = paramiko.SSHClient() - ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - ssh.connect(self.ssh_host, port=self.ssh_port, username=self.ssh_user, key_filename=self.ssh_key_path) - - elan_path: str = "/usr/local/elan/bin/elan" - lean_path: str = "/usr/local/elan/bin/lean" - - stdin, stdout, stderr = ssh.exec_command(f"{elan_path} default stable && {lean_path} --version") - output: str = stdout.read().decode() - error: str = stderr.read().decode() - print("SSH Command Output:", output) - print("SSH Command Error:", error) - - sftp = ssh.open_sftp() - remote_path: str = f"/root/{os.path.basename(filepath)}" - sftp.put(filepath, remote_path) - sftp.close() - - stdin, stdout, stderr = ssh.exec_command(f"{lean_path} {remote_path}") - output = stdout.read().decode() - error = stderr.read().decode() - - ssh.exec_command(f"rm {remote_path}") - ssh.close() - - if "error" in output.lower() or "error" in error.lower(): - return output, {'status': 'failure'} - elif not output and not error: - return "Lean program halted successfully with no output.", {'status': 'success'} - else: - return output, {'status': 'success'} - - except Exception as e: - raise RuntimeError(f"SSH command execution failed: {str(e)}") - - def prepare(self, argument: Any) -> None: - """ - Prepares the input for Lean execution by processing and converting it into the appropriate format. - - Args: - argument (Any): The input to be processed and prepared. - """ - argument.prop.prepared_input = str(argument.prop.processed_input) diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/__init__.py b/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/__init__.py deleted file mode 100644 index cfc1762d0a5659a8c913cb6174191f32c68748c6..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -from ...mixin import (ANTHROPIC_CHAT_MODELS, ANTHROPIC_REASONING_MODELS, - DEEPSEEK_CHAT_MODELS, DEEPSEEK_REASONING_MODELS, - GOOGLE_CHAT_MODELS, GOOGLE_REASONING_MODELS, - OPENAI_CHAT_MODELS, OPENAI_REASONING_MODELS) -from .engine_anthropic_claudeX_chat import ClaudeXChatEngine -from .engine_anthropic_claudeX_reasoning import ClaudeXReasoningEngine -from .engine_deepseekX_reasoning import DeepSeekXReasoningEngine -from .engine_google_geminiX_reasoning import GeminiXReasoningEngine -from .engine_openai_gptX_chat import GPTXChatEngine -from .engine_openai_gptX_reasoning import GPTXReasoningEngine - -# create the mapping -ENGINE_MAPPING = { - **{model_name: ClaudeXChatEngine for model_name in ANTHROPIC_CHAT_MODELS}, - **{model_name: ClaudeXReasoningEngine for model_name in ANTHROPIC_REASONING_MODELS}, - **{model_name: DeepSeekXReasoningEngine for model_name in DEEPSEEK_REASONING_MODELS}, - **{model_name: GeminiXReasoningEngine for model_name in GOOGLE_REASONING_MODELS}, - **{model_name: GPTXChatEngine for model_name in OPENAI_CHAT_MODELS}, - **{model_name: GPTXReasoningEngine for model_name in OPENAI_REASONING_MODELS}, -} diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_anthropic_claudeX_chat.py b/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_anthropic_claudeX_chat.py deleted file mode 100644 index fa20d1f43a2dd4f074989eabb8b1ba33b0cbf4ff..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_anthropic_claudeX_chat.py +++ /dev/null @@ -1,415 +0,0 @@ -import json -import logging -import re -from copy import copy, deepcopy -from typing import List, Optional - -import anthropic -from anthropic._types import NOT_GIVEN -from anthropic.types import (InputJSONDelta, Message, - RawContentBlockDeltaEvent, - RawContentBlockStartEvent, - RawContentBlockStopEvent, TextBlock, TextDelta, - ToolUseBlock) - -from ....components import SelfPrompt -from ....misc.console import ConsoleStyle -from ....symbol import Symbol -from ....utils import CustomUserWarning, encode_media_frames -from ...base import Engine -from ...mixin.anthropic import AnthropicMixin -from ...settings import SYMAI_CONFIG - -logging.getLogger("anthropic").setLevel(logging.ERROR) -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - -class TokenizerWrapper: - def __init__(self, compute_tokens_func): - self.compute_tokens_func = compute_tokens_func - - def encode(self, text: str) -> int: - return self.compute_tokens_func([{"role": "user", "content": text}]) - -class ClaudeXChatEngine(Engine, AnthropicMixin): - def __init__(self, api_key: Optional[str] = None, model: Optional[str] = None): - super().__init__() - self.config = deepcopy(SYMAI_CONFIG) - # In case we use EngineRepository.register to inject the api_key and model => dynamically change the engine at runtime - if api_key is not None and model is not None: - self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] = api_key - self.config['NEUROSYMBOLIC_ENGINE_MODEL'] = model - if self.id() != 'neurosymbolic': - return # do not initialize if not neurosymbolic; avoids conflict with llama.cpp check in EngineRepository.register_from_package - anthropic.api_key = self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] - self.model = self.config['NEUROSYMBOLIC_ENGINE_MODEL'] - self.name = self.__class__.__name__ - self.tokenizer = TokenizerWrapper(self.compute_required_tokens) - self.max_context_tokens = self.api_max_context_tokens() - self.max_response_tokens = self.api_max_response_tokens() - self.client = anthropic.Anthropic(api_key=anthropic.api_key) - - def id(self) -> str: - if self.config.get('NEUROSYMBOLIC_ENGINE_MODEL') and \ - self.config.get('NEUROSYMBOLIC_ENGINE_MODEL').startswith('claude') and \ - ('3-7' not in self.config.get('NEUROSYMBOLIC_ENGINE_MODEL') and \ - '4-0' not in self.config.get('NEUROSYMBOLIC_ENGINE_MODEL')): - return 'neurosymbolic' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'NEUROSYMBOLIC_ENGINE_API_KEY' in kwargs: - anthropic.api_key = kwargs['NEUROSYMBOLIC_ENGINE_API_KEY'] - if 'NEUROSYMBOLIC_ENGINE_MODEL' in kwargs: - self.model = kwargs['NEUROSYMBOLIC_ENGINE_MODEL'] - - def compute_required_tokens(self, messages) -> int: - claude_messages = [] - system_content = None - - for msg in messages: - if not isinstance(msg, list): - msg = [msg] - for part in msg: - if isinstance(part, str): - role = 'user' - content_str = part - elif isinstance(part, dict): - role = part.get('role') - content_str = str(part.get('content', '')) - else: - CustomUserWarning(f"Unsupported message part type: {type(part)}", raise_with=ValueError) - - if role == 'system': - system_content = content_str - continue - - if role in ['user', 'assistant']: - message_content = [] - - image_content = self._handle_image_content(content_str) - message_content.extend(image_content) - - text_content = self._remove_vision_pattern(content_str) - if text_content: - message_content.append({ - "type": "text", - "text": text_content - }) - - if message_content: - if len(message_content) == 1 and message_content[0].get('type') == 'text': - claude_messages.append({ - 'role': role, - 'content': message_content[0]['text'] - }) - else: - claude_messages.append({ - 'role': role, - 'content': message_content - }) - - if not claude_messages: - return 0 - - try: - count_params = { - 'model': self.model, - 'messages': claude_messages - } - if system_content: - count_params['system'] = system_content - count_response = self.client.messages.count_tokens(**count_params) - return count_response.input_tokens - except Exception as e: - logging.error(f"Claude count_tokens failed: {e}") - CustomUserWarning(f"Error counting tokens for Claude: {str(e)}", raise_with=RuntimeError) - - def compute_remaining_tokens(self, prompts: list) -> int: - raise NotImplementedError('Method not implemented.') - - def _handle_image_content(self, content: str) -> list: - """Handle image content by processing vision patterns and returning image file data.""" - def extract_pattern(text): - pattern = r'<>' - return re.findall(pattern, text) - - image_files = [] - if '< 1: - step = len(buffer) // max_frames_spacing # max frames spacing - frames = [] - indices = list(range(0, len(buffer), step))[:max_used_frames] - for i in indices: - frames.append({'data': buffer[i], 'media_type': f'image/{ext}', 'type': 'base64'}) - image_files.extend(frames) - elif len(buffer) == 1: - image_files.append({'data': buffer[0], 'media_type': f'image/{ext}', 'type': 'base64'}) - else: - CustomUserWarning(f'No frames found for image!') - return image_files - - def _remove_vision_pattern(self, text: str) -> str: - """Remove vision patterns from text.""" - pattern = r'<>' - return re.sub(pattern, '', text) - - def forward(self, argument): - kwargs = argument.kwargs - system, messages = argument.prop.prepared_input - payload = self._prepare_request_payload(argument) - except_remedy = kwargs.get('except_remedy') - - try: - res = self.client.messages.create( - system=system, - messages=messages, - **payload - ) - except Exception as e: - if anthropic.api_key is None or anthropic.api_key == '': - msg = 'Anthropic API key is not set. Please set it in the config file or pass it as an argument to the command method.' - logging.error(msg) - if self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] is None or self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] == '': - CustomUserWarning(msg, raise_with=ValueError) - anthropic.api_key = self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] - - callback = self.client.messages.create - kwargs['model'] = kwargs['model'] if 'model' in kwargs else self.model - - if except_remedy is not None: - res = except_remedy(self, e, callback, argument) - else: - CustomUserWarning(f"Anthropic API request failed: {e}", raise_with=ValueError) - - if payload['stream']: - res = [_ for _ in res] # Unpack the iterator to a list - metadata = {'raw_output': res} - response_data = self._collect_response(res) - - if response_data.get('function_call'): - metadata['function_call'] = response_data['function_call'] - - text_output = response_data.get('text', '') - if argument.prop.response_format: - # Anthropic returns JSON in markdown format - text_output = text_output.replace('```json', '').replace('```', '') - - return [text_output], metadata - - def _prepare_raw_input(self, argument): - if not argument.prop.processed_input: - raise ValueError('Need to provide a prompt instruction to the engine if `raw_input` is enabled!') - system = NOT_GIVEN - prompt = copy(argument.prop.processed_input) - if type(prompt) != list: - if type(prompt) != dict: - prompt = {'role': 'user', 'content': str(prompt)} - prompt = [prompt] - if len(prompt) > 1: - # assert there are not more than 1 system instruction - assert len([p for p in prompt if p['role'] == 'system']) <= 1, 'Only one system instruction is allowed!' - for p in prompt: - if p['role'] == 'system': - system = p['content'] - prompt.remove(p) - break - return system, prompt - - def prepare(self, argument): - #@NOTE: OpenAI compatibility at high level - if argument.prop.raw_input: - argument.prop.prepared_input = self._prepare_raw_input(argument) - return - - _non_verbose_output = """\nYou do not output anything else, like verbose preambles or post explanation, such as "Sure, let me...", "Hope that was helpful...", "Yes, I can help you with that...", etc. Consider well formatted output, e.g. for sentences use punctuation, spaces etc. or for code use indentation, etc. Never add meta instructions information to your output!\n\n""" - user: str = "" - system: str = "" - - if argument.prop.suppress_verbose_output: - system += _non_verbose_output - system = f'{system}\n' if system and len(system) > 0 else '' - - if argument.prop.response_format: - _rsp_fmt = argument.prop.response_format - assert _rsp_fmt.get('type') is not None, 'Response format type is required! Expected format `{"type": str}`! The str value will be passed to the engine. Refer to the Anthropic documentation for more information: https://docs.anthropic.com/en/docs/test-and-evaluate/strengthen-guardrails/increase-consistency#example-standardizing-customer-feedback' - system += _non_verbose_output - system += f'\n{_rsp_fmt["type"]}\n\n' - - ref = argument.prop.instance - static_ctxt, dyn_ctxt = ref.global_context - if len(static_ctxt) > 0: - system += f"\n{static_ctxt}\n\n" - - if len(dyn_ctxt) > 0: - system += f"\n{dyn_ctxt}\n\n" - - payload = argument.prop.payload - if argument.prop.payload: - system += f"\n{str(payload)}\n\n" - - examples: List[str] = argument.prop.examples - if examples and len(examples) > 0: - system += f"\n{str(examples)}\n\n" - - image_files = self._handle_image_content(str(argument.prop.processed_input)) - - if argument.prop.prompt is not None and len(argument.prop.prompt) > 0: - val = str(argument.prop.prompt) - if len(image_files) > 0: - val = self._remove_vision_pattern(val) - system += f"\n{val}\n\n" - - suffix: str = str(argument.prop.processed_input) - if len(image_files) > 0: - suffix = self._remove_vision_pattern(suffix) - - user += f"{suffix}" - - if not len(user): - # Anthropic doesn't allow empty user prompts; force it - user = "N/A" - - if argument.prop.template_suffix: - system += f' You will only generate content for the placeholder `{str(argument.prop.template_suffix)}` following the instructions and the provided context information.\n\n' - - if len(image_files) > 0: - images = [{ 'type': 'image', "source": im } for im in image_files] - user_prompt = { "role": "user", "content": [ - *images, - { 'type': 'text', 'text': user } - ]} - else: - user_prompt = { "role": "user", "content": user } - - # First check if the `Symbol` instance has the flag set, otherwise check if it was passed as an argument to a method - if argument.prop.instance._kwargs.get('self_prompt', False) or argument.prop.self_prompt: - self_prompter = SelfPrompt() - - res = self_prompter({'user': user, 'system': system}) - if res is None: - raise ValueError("Self-prompting failed!") - - if len(image_files) > 0: - user_prompt = { "role": "user", "content": [ - *images, - { 'type': 'text', 'text': res['user'] } - ]} - else: - user_prompt = { "role": "user", "content": res['user'] } - - system = res['system'] - - argument.prop.prepared_input = (system, [user_prompt]) - - def _prepare_request_payload(self, argument): - kwargs = argument.kwargs - model = kwargs.get('model', self.model) - max_tokens = kwargs.get('max_tokens', self.max_response_tokens) - stop = kwargs.get('stop', NOT_GIVEN) - temperature = kwargs.get('temperature', 1) - top_p = kwargs.get('top_p', NOT_GIVEN if temperature is not None else 1) #@NOTE:'You should either alter temperature or top_p, but not both.' - top_k = kwargs.get('top_k', NOT_GIVEN) - stream = kwargs.get('stream', True) # Do NOT remove this default value! Getting tons of API errors because they can't process requests >10m - tools = kwargs.get('tools', NOT_GIVEN) - tool_choice = kwargs.get('tool_choice', NOT_GIVEN) - metadata_anthropic = kwargs.get('metadata', NOT_GIVEN) - - if stop != NOT_GIVEN and type(stop) != list: - stop = [stop] - - #@NOTE: Anthropic fails if stop is not raw string, so cast it to r'…' - # E.g. when we use defaults in core.py, i.e. stop=['\n'] - if stop != NOT_GIVEN: - stop = [r'{s}' for s in stop] - - return { - "model": model, - "max_tokens": max_tokens, - "stop_sequences": stop, - "temperature": temperature, - "top_p": top_p, - "top_k": top_k, - "stream": stream, - "metadata": metadata_anthropic, - "tools": tools, - "tool_choice": tool_choice - } - - def _collect_response(self, res): - if isinstance(res, list): - text_content = '' - tool_calls_raw = [] - active_tool_calls = {} - - for chunk in res: - if isinstance(chunk, RawContentBlockStartEvent): - if isinstance(chunk.content_block, ToolUseBlock): - active_tool_calls[chunk.index] = { - 'id': chunk.content_block.id, - 'name': chunk.content_block.name, - 'input_json_str': "" - } - elif isinstance(chunk, RawContentBlockDeltaEvent): - if isinstance(chunk.delta, TextDelta): - text_content += chunk.delta.text - elif isinstance(chunk.delta, InputJSONDelta): - if chunk.index in active_tool_calls: - active_tool_calls[chunk.index]['input_json_str'] += chunk.delta.partial_json - elif isinstance(chunk, RawContentBlockStopEvent): - if chunk.index in active_tool_calls: - tool_call_info = active_tool_calls.pop(chunk.index) - try: - tool_call_info['input'] = json.loads(tool_call_info['input_json_str']) - except json.JSONDecodeError as e: - logging.error(f"Failed to parse JSON for tool call {tool_call_info['name']}: {e}. Raw JSON: '{tool_call_info['input_json_str']}'") - tool_call_info['input'] = {} - tool_calls_raw.append(tool_call_info) - - function_call_data = None - if tool_calls_raw: - if len(tool_calls_raw) > 1: - CustomUserWarning("Multiple tool calls detected in the stream but only the first one will be processed.") - function_call_data = { - 'name': tool_calls_raw[0]['name'], - 'arguments': tool_calls_raw[0]['input'] - } - - return { - "text": text_content, - "function_call": function_call_data - } - - # Non-streamed response (res is a Message object) - if isinstance(res, Message): - text_content = '' - function_call_data = None - hit_tool_use = False - - for content_block in res.content: - if isinstance(content_block, TextBlock): - text_content += content_block.text - elif isinstance(content_block, ToolUseBlock): - if hit_tool_use: - CustomUserWarning("Multiple tool use blocks detected in the response but only the first one will be processed.") - else: - function_call_data = { - 'name': content_block.name, - 'arguments': content_block.input - } - hit_tool_use = True - return { - "text": text_content, - "function_call": function_call_data - } - - CustomUserWarning(f"Unexpected response type from Anthropic API: {type(res)}", raise_with=ValueError) diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_anthropic_claudeX_reasoning.py b/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_anthropic_claudeX_reasoning.py deleted file mode 100644 index 4b9d2808d359b3d65f8989b2ea7e214dee99dbbd..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_anthropic_claudeX_reasoning.py +++ /dev/null @@ -1,440 +0,0 @@ -import json -import logging -import re -from copy import copy, deepcopy -from typing import List, Optional - -import anthropic -from anthropic._types import NOT_GIVEN -from anthropic.types import (InputJSONDelta, Message, - RawContentBlockDeltaEvent, - RawContentBlockStartEvent, - RawContentBlockStopEvent, TextBlock, TextDelta, - ThinkingBlock, ThinkingDelta, ToolUseBlock) - -from ....components import SelfPrompt -from ....misc.console import ConsoleStyle -from ....symbol import Symbol -from ....utils import CustomUserWarning, encode_media_frames -from ...base import Engine -from ...mixin.anthropic import AnthropicMixin -from ...settings import SYMAI_CONFIG - -logging.getLogger("anthropic").setLevel(logging.ERROR) -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - - -class TokenizerWrapper: - def __init__(self, compute_tokens_func): - self.compute_tokens_func = compute_tokens_func - - def encode(self, text: str) -> int: - return self.compute_tokens_func([{"role": "user", "content": text}]) - -class ClaudeXReasoningEngine(Engine, AnthropicMixin): - def __init__(self, api_key: Optional[str] = None, model: Optional[str] = None): - super().__init__() - self.config = deepcopy(SYMAI_CONFIG) - # In case we use EngineRepository.register to inject the api_key and model => dynamically change the engine at runtime - if api_key is not None and model is not None: - self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] = api_key - self.config['NEUROSYMBOLIC_ENGINE_MODEL'] = model - if self.id() != 'neurosymbolic': - return # do not initialize if not neurosymbolic; avoids conflict with llama.cpp check in EngineRepository.register_from_package - anthropic.api_key = self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] - self.model = self.config['NEUROSYMBOLIC_ENGINE_MODEL'] - self.name = self.__class__.__name__ - self.tokenizer = TokenizerWrapper(self.compute_required_tokens) - self.max_context_tokens = self.api_max_context_tokens() - self.max_response_tokens = self.api_max_response_tokens() - self.client = anthropic.Anthropic(api_key=anthropic.api_key) - - def id(self) -> str: - if self.config.get('NEUROSYMBOLIC_ENGINE_MODEL') and \ - self.config.get('NEUROSYMBOLIC_ENGINE_MODEL').startswith('claude') and \ - ('3-7' in self.config.get('NEUROSYMBOLIC_ENGINE_MODEL') or \ - '4-0' in self.config.get('NEUROSYMBOLIC_ENGINE_MODEL')): - return 'neurosymbolic' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'NEUROSYMBOLIC_ENGINE_API_KEY' in kwargs: - anthropic.api_key = kwargs['NEUROSYMBOLIC_ENGINE_API_KEY'] - if 'NEUROSYMBOLIC_ENGINE_MODEL' in kwargs: - self.model = kwargs['NEUROSYMBOLIC_ENGINE_MODEL'] - - def compute_required_tokens(self, messages) -> int: - claude_messages = [] - system_content = None - - for msg in messages: - if not isinstance(msg, list): - msg = [msg] - for part in msg: - if isinstance(part, str): - role = 'user' - content_str = part - elif isinstance(part, dict): - role = part.get('role') - content_str = str(part.get('content', '')) - else: - CustomUserWarning(f"Unsupported message part type: {type(part)}", raise_with=ValueError) - - if role == 'system': - system_content = content_str - continue - - if role in ['user', 'assistant']: - message_content = [] - - image_content = self._handle_image_content(content_str) - message_content.extend(image_content) - - text_content = self._remove_vision_pattern(content_str) - if text_content: - message_content.append({ - "type": "text", - "text": text_content - }) - - if message_content: - if len(message_content) == 1 and message_content[0].get('type') == 'text': - claude_messages.append({ - 'role': role, - 'content': message_content[0]['text'] - }) - else: - claude_messages.append({ - 'role': role, - 'content': message_content - }) - - if not claude_messages: - return 0 - - try: - count_params = { - 'model': self.model, - 'messages': claude_messages - } - if system_content: - count_params['system'] = system_content - count_response = self.client.messages.count_tokens(**count_params) - return count_response.input_tokens - except Exception as e: - logging.error(f"Claude count_tokens failed: {e}") - CustomUserWarning(f"Error counting tokens for Claude: {str(e)}", raise_with=RuntimeError) - - def compute_remaining_tokens(self, prompts: list) -> int: - CustomUserWarning('Method not implemented.', raise_with=NotImplementedError) - - def _handle_image_content(self, content: str) -> list: - """Handle image content by processing vision patterns and returning image file data.""" - def extract_pattern(text): - pattern = r'<>' - return re.findall(pattern, text) - - image_files = [] - if '< 1: - step = len(buffer) // max_frames_spacing # max frames spacing - frames = [] - indices = list(range(0, len(buffer), step))[:max_used_frames] - for i in indices: - frames.append({'data': buffer[i], 'media_type': f'image/{ext}', 'type': 'base64'}) - image_files.extend(frames) - elif len(buffer) == 1: - image_files.append({'data': buffer[0], 'media_type': f'image/{ext}', 'type': 'base64'}) - else: - CustomUserWarning(f'No frames found for image!') - return image_files - - def _remove_vision_pattern(self, text: str) -> str: - """Remove vision patterns from text.""" - pattern = r'<>' - return re.sub(pattern, '', text) - - def forward(self, argument): - kwargs = argument.kwargs - system, messages = argument.prop.prepared_input - payload = self._prepare_request_payload(argument) - except_remedy = kwargs.get('except_remedy') - - try: - res = self.client.messages.create( - system=system, - messages=messages, - **payload - ) - except Exception as e: - if anthropic.api_key is None or anthropic.api_key == '': - msg = 'Anthropic API key is not set. Please set it in the config file or pass it as an argument to the command method.' - logging.error(msg) - if self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] is None or self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] == '': - CustomUserWarning(msg, raise_with=ValueError) - anthropic.api_key = self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] - - callback = self.client.messages.create - kwargs['model'] = kwargs['model'] if 'model' in kwargs else self.model - - if except_remedy is not None: - res = except_remedy(self, e, callback, argument) - else: - CustomUserWarning(f"Anthropic API request failed: {e}", raise_with=ValueError) - - if payload['stream']: - res = [_ for _ in res] # Unpack the iterator to a list - metadata = {'raw_output': res} - response_data = self._collect_response(res) - - if response_data.get('function_call'): - metadata['function_call'] = response_data['function_call'] - - if response_data.get('thinking') and len(response_data['thinking']) > 0: - metadata['thinking'] = response_data['thinking'] - - text_output = response_data.get('text', '') - if argument.prop.response_format: - # Anthropic returns JSON in markdown format - text_output = text_output.replace('```json', '').replace('```', '') - - return [text_output], metadata - - def _prepare_raw_input(self, argument): - if not argument.prop.processed_input: - raise ValueError('Need to provide a prompt instruction to the engine if `raw_input` is enabled!') - system = NOT_GIVEN - prompt = copy(argument.prop.processed_input) - if type(prompt) != list: - if type(prompt) != dict: - prompt = {'role': 'user', 'content': str(prompt)} - prompt = [prompt] - if len(prompt) > 1: - # assert there are not more than 1 system instruction - assert len([p for p in prompt if p['role'] == 'system']) <= 1, 'Only one system instruction is allowed!' - for p in prompt: - if p['role'] == 'system': - system = p['content'] - prompt.remove(p) - break - return system, prompt - - def prepare(self, argument): - #@NOTE: OpenAI compatibility at high level - if argument.prop.raw_input: - argument.prop.prepared_input = self._prepare_raw_input(argument) - return - - _non_verbose_output = """\nYou do not output anything else, like verbose preambles or post explanation, such as "Sure, let me...", "Hope that was helpful...", "Yes, I can help you with that...", etc. Consider well formatted output, e.g. for sentences use punctuation, spaces etc. or for code use indentation, etc. Never add meta instructions information to your output!\n\n""" - user: str = "" - system: str = "" - - if argument.prop.suppress_verbose_output: - system += _non_verbose_output - system = f'{system}\n' if system and len(system) > 0 else '' - - if argument.prop.response_format: - _rsp_fmt = argument.prop.response_format - if not (_rsp_fmt.get('type') is not None): - CustomUserWarning('Response format type is required! Expected format `{"type": "json_object"}` or other supported types. Refer to Anthropic documentation for details.', raise_with=AssertionError) - system += _non_verbose_output - system += f'\n{_rsp_fmt["type"]}\n\n' - - ref = argument.prop.instance - static_ctxt, dyn_ctxt = ref.global_context - if len(static_ctxt) > 0: - system += f"\n{static_ctxt}\n\n" - - if len(dyn_ctxt) > 0: - system += f"\n{dyn_ctxt}\n\n" - - payload = argument.prop.payload - if argument.prop.payload: - system += f"\n{str(payload)}\n\n" - - examples: List[str] = argument.prop.examples - if examples and len(examples) > 0: - system += f"\n{str(examples)}\n\n" - - image_files = self._handle_image_content(str(argument.prop.processed_input)) - - if argument.prop.prompt is not None and len(argument.prop.prompt) > 0: - val = str(argument.prop.prompt) - if len(image_files) > 0: - val = self._remove_vision_pattern(val) - system += f"\n{val}\n\n" - - suffix: str = str(argument.prop.processed_input) - if len(image_files) > 0: - suffix = self._remove_vision_pattern(suffix) - - user += f"{suffix}" - - if not len(user): - # Anthropic doesn't allow empty user prompts; force it - user = "N/A" - - if argument.prop.template_suffix: - system += f' You will only generate content for the placeholder `{str(argument.prop.template_suffix)}` following the instructions and the provided context information.\n\n' - - if len(image_files) > 0: - images = [{ 'type': 'image', "source": im } for im in image_files] - user_prompt = { "role": "user", "content": [ - *images, - { 'type': 'text', 'text': user } - ]} - else: - user_prompt = { "role": "user", "content": user } - - # First check if the `Symbol` instance has the flag set, otherwise check if it was passed as an argument to a method - if argument.prop.instance._kwargs.get('self_prompt', False) or argument.prop.self_prompt: - self_prompter = SelfPrompt() - - res = self_prompter( - {'user': user, 'system': system}, - max_tokens=argument.kwargs.get('max_tokens', self.max_response_tokens), - thinking=argument.kwargs.get('thinking', NOT_GIVEN), - ) - if res is None: - CustomUserWarning("Self-prompting failed to return a response.", raise_with=ValueError) - - if len(image_files) > 0: - user_prompt = { "role": "user", "content": [ - *images, - { 'type': 'text', 'text': res['user'] } - ]} - else: - user_prompt = { "role": "user", "content": res['user'] } - - system = res['system'] - - argument.prop.prepared_input = (system, [user_prompt]) - - def _prepare_request_payload(self, argument): - kwargs = argument.kwargs - model = kwargs.get('model', self.model) - stop = kwargs.get('stop', NOT_GIVEN) - temperature = kwargs.get('temperature', 1) - thinking_arg = kwargs.get('thinking', NOT_GIVEN) - thinking = NOT_GIVEN - if thinking_arg and isinstance(thinking_arg, dict): - thinking = { - "type": "enabled", - "budget_tokens": thinking_arg.get("budget_tokens", 1024) - } - top_p = kwargs.get('top_p', NOT_GIVEN if temperature is not None else 1) #@NOTE:'You should either alter temperature or top_p, but not both.' - top_k = kwargs.get('top_k', NOT_GIVEN) - stream = kwargs.get('stream', True) # Do NOT remove this default value! Getting tons of API errors because they can't process requests >10m - tools = kwargs.get('tools', NOT_GIVEN) - tool_choice = kwargs.get('tool_choice', NOT_GIVEN) - metadata_anthropic = kwargs.get('metadata', NOT_GIVEN) - max_tokens = kwargs.get('max_tokens', self.max_response_tokens) - - if stop != NOT_GIVEN and type(stop) != list: - stop = [stop] - - #@NOTE: Anthropic fails if stop is not raw string, so cast it to r'…' - # E.g. when we use defaults in core.py, i.e. stop=['\n'] - if stop != NOT_GIVEN: - stop = [r'{s}' for s in stop] - - return { - "model": model, - "max_tokens": max_tokens, - "stop_sequences": stop, - "temperature": temperature, - "thinking": thinking, - "top_p": top_p, - "top_k": top_k, - "stream": stream, - "metadata": metadata_anthropic, - "tools": tools, - "tool_choice": tool_choice - } - - def _collect_response(self, res): - if isinstance(res, list): - thinking_content = '' - text_content = '' - tool_calls_raw = [] - active_tool_calls = {} - - for chunk in res: - if isinstance(chunk, RawContentBlockStartEvent): - if isinstance(chunk.content_block, ToolUseBlock): - active_tool_calls[chunk.index] = { - 'id': chunk.content_block.id, - 'name': chunk.content_block.name, - 'input_json_str': "" - } - elif isinstance(chunk, RawContentBlockDeltaEvent): - if isinstance(chunk.delta, ThinkingDelta): - thinking_content += chunk.delta.thinking - elif isinstance(chunk.delta, TextDelta): - text_content += chunk.delta.text - elif isinstance(chunk.delta, InputJSONDelta): - if chunk.index in active_tool_calls: - active_tool_calls[chunk.index]['input_json_str'] += chunk.delta.partial_json - elif isinstance(chunk, RawContentBlockStopEvent): - if chunk.index in active_tool_calls: - tool_call_info = active_tool_calls.pop(chunk.index) - try: - tool_call_info['input'] = json.loads(tool_call_info['input_json_str']) - except json.JSONDecodeError as e: - logging.error(f"Failed to parse JSON for tool call {tool_call_info['name']}: {e}. Raw JSON: '{tool_call_info['input_json_str']}'") - tool_call_info['input'] = {} - tool_calls_raw.append(tool_call_info) - - function_call_data = None - if tool_calls_raw: - if len(tool_calls_raw) > 1: - CustomUserWarning("Multiple tool calls detected in the stream but only the first one will be processed.") - function_call_data = { - 'name': tool_calls_raw[0]['name'], - 'arguments': tool_calls_raw[0]['input'] - } - - return { - "thinking": thinking_content, - "text": text_content, - "function_call": function_call_data - } - - # Non-streamed response (res is a Message object) - if isinstance(res, Message): - thinking_content = '' - text_content = '' - function_call_data = None - hit = False - - for content_block in res.content: - if isinstance(content_block, ThinkingBlock): - thinking_content += content_block.thinking - elif isinstance(content_block, TextBlock): - text_content += content_block.text - elif isinstance(content_block, ToolUseBlock): - if hit: - CustomUserWarning("Multiple tool use blocks detected in the response but only the first one will be processed.") - else: - function_call_data = { - 'name': content_block.name, - 'arguments': content_block.input - } - hit = True - return { - "thinking": thinking_content, - "text": text_content, - "function_call": function_call_data - } - - CustomUserWarning(f"Unexpected response type from Anthropic API: {type(res)}", raise_with=ValueError) diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_deepseekX_reasoning.py b/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_deepseekX_reasoning.py deleted file mode 100644 index cd1a0c4ede9e5195e944932a368b18392ebbd510..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_deepseekX_reasoning.py +++ /dev/null @@ -1,189 +0,0 @@ -import logging -import re -from copy import deepcopy -from typing import List, Optional - -from annotated_types import Not -from openai import OpenAI - -from ....components import SelfPrompt -from ....misc.console import ConsoleStyle -from ....symbol import Symbol -from ....utils import CustomUserWarning, encode_media_frames -from ...base import Engine -from ...mixin.deepseek import DeepSeekMixin -from ...settings import SYMAI_CONFIG - -logging.getLogger("openai").setLevel(logging.ERROR) -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - - -class DeepSeekXReasoningEngine(Engine, DeepSeekMixin): - def __init__(self, api_key: Optional[str] = None, model: Optional[str] = None): - super().__init__() - self.config = deepcopy(SYMAI_CONFIG) - # In case we use EngineRepository.register to inject the api_key and model => dynamically change the engine at runtime - if api_key is not None and model is not None: - self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] = api_key - self.config['NEUROSYMBOLIC_ENGINE_MODEL'] = model - if self.id() != 'neurosymbolic': - return # do not initialize if not neurosymbolic; avoids conflict with llama.cpp check in EngineRepository.register_from_package - self.api_key = self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] - self.model = self.config['NEUROSYMBOLIC_ENGINE_MODEL'] - self.name = self.__class__.__name__ - self.tokenizer = None - self.max_context_tokens = self.api_max_context_tokens() - self.max_response_tokens = self.api_max_response_tokens() - self.seed = None - - try: - self.client = OpenAI(api_key=self.api_key, base_url="https://api.deepseek.com") - except Exception as e: - CustomUserWarning(f'Failed to initialize the DeepSeek client. Please check your library version. Caused by: {e}', raise_with=RuntimeError) - - def id(self) -> str: - if self.config.get('NEUROSYMBOLIC_ENGINE_MODEL') and \ - self.config.get('NEUROSYMBOLIC_ENGINE_MODEL').startswith('deepseek'): - return 'neurosymbolic' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'NEUROSYMBOLIC_ENGINE_API_KEY' in kwargs: - self.api_key = kwargs['NEUROSYMBOLIC_ENGINE_API_KEY'] - if 'NEUROSYMBOLIC_ENGINE_MODEL' in kwargs: - self.model = kwargs['NEUROSYMBOLIC_ENGINE_MODEL'] - if 'seed' in kwargs: - self.seed = kwargs['seed'] - - def compute_required_tokens(self, messages): - CustomUserWarning('Method "compute_required_tokens" not implemented for DeepSeekXReasoningEngine.', raise_with=NotImplementedError) - - def compute_remaining_tokens(self, prompts: list) -> int: - CustomUserWarning('Method "compute_remaining_tokens" not implemented for DeepSeekXReasoningEngine.', raise_with=NotImplementedError) - - def truncate(self, prompts: list[dict], truncation_percentage: float | None, truncation_type: str) -> list[dict]: - CustomUserWarning('Method "truncate" not implemented for DeepSeekXReasoningEngine.', raise_with=NotImplementedError) - - def forward(self, argument): - kwargs = argument.kwargs - messages = argument.prop.prepared_input - payload = self._prepare_request_payload(argument) - except_remedy = kwargs.get('except_remedy') - - try: - res = self.client.chat.completions.create(messages=messages, **payload) - - except Exception as e: - if self.api_key is None or self.api_key == '': - msg = 'DeepSeek API key is not set. Please set it in the config file or pass it as an argument to the command method.' - logging.error(msg) - if self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] is None or self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] == '': - CustomUserWarning(msg, raise_with=ValueError) - self.api_key = self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] - - callback = self.client.chat.completions.create - kwargs['model'] = kwargs['model'] if 'model' in kwargs else self.model - - if except_remedy is not None: - res = except_remedy(self, e, callback, argument) - else: - CustomUserWarning(f"DeepSeek API request failed. Original error: {e}", raise_with=ValueError) - - reasoning_content = res.choices[0].message.reasoning_content - content = res.choices[0].message.content - metadata = {'raw_output': res, 'thinking': reasoning_content} - - return [content], metadata - - def _prepare_raw_input(self, argument): - if not argument.prop.processed_input: - CustomUserWarning('A prompt instruction is required for DeepSeekXReasoningEngine when raw_input is enabled.', raise_with=ValueError) - value = argument.prop.processed_input - # convert to dict if not already - if type(value) != list: - if type(value) != dict: - value = {'role': 'user', 'content': str(value)} - value = [value] - return value - - def prepare(self, argument): - if argument.prop.raw_input: - argument.prop.prepared_input = self._prepare_raw_input(argument) - return - - _non_verbose_output = """\nYou do not output anything else, like verbose preambles or post explanation, such as "Sure, let me...", "Hope that was helpful...", "Yes, I can help you with that...", etc. Consider well formatted output, e.g. for sentences use punctuation, spaces etc. or for code use indentation, etc. Never add meta instructions information to your output!\n\n""" - user: str = "" - system: str = "" - - if argument.prop.suppress_verbose_output: - system += _non_verbose_output - system = f'{system}\n' if system and len(system) > 0 else '' - - if argument.prop.response_format: - _rsp_fmt = argument.prop.response_format - if not (_rsp_fmt.get('type') is not None): - CustomUserWarning('Response format type is required! Expected format `{"type": "json_object"}` or other supported types.', raise_with=AssertionError) - system += _non_verbose_output - system += f'\n{_rsp_fmt["type"]}\n\n' - - ref = argument.prop.instance - static_ctxt, dyn_ctxt = ref.global_context - if len(static_ctxt) > 0: - system += f"\n{static_ctxt}\n\n" - - if len(dyn_ctxt) > 0: - system += f"\n{dyn_ctxt}\n\n" - - payload = argument.prop.payload - if argument.prop.payload: - system += f"\n{str(payload)}\n\n" - - examples: List[str] = argument.prop.examples - if examples and len(examples) > 0: - system += f"\n{str(examples)}\n\n" - - if argument.prop.prompt is not None and len(argument.prop.prompt) > 0: - val = str(argument.prop.prompt) - system += f"\n{val}\n\n" - - user += f"{str(argument.prop.processed_input)}" - - if argument.prop.template_suffix: - system += f' You will only generate content for the placeholder `{str(argument.prop.template_suffix)}` following the instructions and the provided context information.\n\n' - - user_prompt = { "role": "user", "content": user } - - # First check if the `Symbol` instance has the flag set, otherwise check if it was passed as an argument to a method - if argument.prop.instance._kwargs.get('self_prompt', False) or argument.prop.self_prompt: - self_prompter = SelfPrompt() - - res = self_prompter({'user': user, 'system': system}) - if res is None: - CustomUserWarning("Self-prompting failed for DeepSeekXReasoningEngine.", raise_with=ValueError) - - user_prompt = { "role": "user", "content": res['user'] } - system = res['system'] - - argument.prop.prepared_input = [ - { "role": "system", "content": system }, - user_prompt, - ] - - def _prepare_request_payload(self, argument): - """Prepares the request payload from the argument.""" - kwargs = argument.kwargs - # 16/03/2025 - # Not Supported Features:Function Call、Json Output、FIM (Beta) - # Not Supported Parameters:temperature、top_p、presence_penalty、frequency_penalty、logprobs、top_logprobs - return { - "model": kwargs.get('model', self.model), - "seed": kwargs.get('seed', self.seed), - "max_tokens": kwargs.get('max_tokens', self.max_response_tokens), - "stop": kwargs.get('stop', '<|endoftext|>'), - "n": kwargs.get('n', 1), - "logit_bias": kwargs.get('logit_bias'), - } diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_google_geminiX_reasoning.py b/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_google_geminiX_reasoning.py deleted file mode 100644 index d17db4a6a0f588bf2091f6ecaf41875be12fa9cd..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_google_geminiX_reasoning.py +++ /dev/null @@ -1,592 +0,0 @@ -import base64 -import io -import logging -import mimetypes -import re -import urllib.parse -from copy import deepcopy -from pathlib import Path - -import requests -from google import genai -from google.genai import types - -from ....components import SelfPrompt -from ....misc.console import ConsoleStyle -from ....symbol import Symbol -from ....utils import CustomUserWarning, encode_media_frames -from ...base import Engine -from ...mixin.google import GoogleMixin -from ...settings import SYMAI_CONFIG - -logging.getLogger("google.genai").setLevel(logging.ERROR) -logging.getLogger("google_genai").propagate = False -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - - -class TokenizerWrapper: - def __init__(self, compute_tokens_func): - self.compute_tokens_func = compute_tokens_func - - def encode(self, text: str) -> int: - return self.compute_tokens_func([{"role": "user", "content": text}]) - -class GeminiXReasoningEngine(Engine, GoogleMixin): - def __init__(self, api_key: str | None = None, model: str | None = None): - super().__init__() - self.config = deepcopy(SYMAI_CONFIG) - # In case we use EngineRepository.register to inject the api_key and model => dynamically change the engine at runtime - if api_key is not None and model is not None: - self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] = api_key - self.config['NEUROSYMBOLIC_ENGINE_MODEL'] = model - if self.id() != 'neurosymbolic': - return # do not initialize if not neurosymbolic; avoids conflict with llama.cpp check in EngineRepository.register_from_package - - self.api_key = self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] - self.model = self.config['NEUROSYMBOLIC_ENGINE_MODEL'] - self.name = self.__class__.__name__ - self.tokenizer = TokenizerWrapper(self.compute_required_tokens) - self.max_context_tokens = self.api_max_context_tokens() - self.max_response_tokens = self.api_max_response_tokens() - self.client = genai.Client(api_key=self.api_key) - - def id(self) -> str: - model = self.config.get('NEUROSYMBOLIC_ENGINE_MODEL') - if model and model.startswith('gemini'): - return 'neurosymbolic' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'NEUROSYMBOLIC_ENGINE_API_KEY' in kwargs: - self.api_key = kwargs['NEUROSYMBOLIC_ENGINE_API_KEY'] - genai.configure(api_key=self.api_key) - if 'NEUROSYMBOLIC_ENGINE_MODEL' in kwargs: - self.model = kwargs['NEUROSYMBOLIC_ENGINE_MODEL'] - self.client = genai.GenerativeModel(model_name=self.model) - - def compute_required_tokens(self, messages) -> int: - api_contents: list[types.Content] = [] - - for msg in messages: - if not isinstance(msg, list): - msg = [msg] - for part in msg: - if isinstance(part, str): - role = 'user' - content_str = part - elif isinstance(part, dict): - role = part.get('role') - content_str = str(part.get('content', '')) - current_message_api_parts: list[types.Part] = [] - image_api_parts = self._handle_image_content(content_str) - current_message_api_parts.extend(image_api_parts) - - text_only_content = self._remove_media_patterns(content_str) - if text_only_content: - current_message_api_parts.append(types.Part(text=text_only_content)) - - if current_message_api_parts: - api_contents.append(types.Content(role=role, parts=current_message_api_parts)) - - if not api_contents: - return 0 - - try: - count_response = self.client.models.count_tokens(model=self.model, contents=api_contents) - return count_response.total_tokens - except Exception as e: - logging.error(f"Gemini count_tokens failed: {e}") - CustomUserWarning(f"Error counting tokens for Gemini: {str(e)}", raise_with=RuntimeError) - - def compute_remaining_tokens(self, prompts: list) -> int: - CustomUserWarning("Token counting not implemented for Gemini", raise_with=NotImplementedError) - - def _handle_document_content(self, content: str): - """Handle document content by uploading to Gemini""" - try: - pattern = r'<>' - matches = re.findall(pattern, content) - if not matches: - return None - - doc_path = matches[0].strip() - if doc_path.startswith('http'): - CustomUserWarning("URL documents not yet supported for Gemini") - return None - else: - uploaded_file = genai.upload_file(doc_path) - return uploaded_file - except Exception as e: - CustomUserWarning(f"Failed to process document: {e}") - return None - - def _handle_image_content(self, content: str) -> list: - """Handle image content by processing and preparing google.generativeai.types.Part objects.""" - image_parts = [] - pattern = r'<>' - matches = re.findall(pattern, content) # re must be imported - - for match in matches: - img_src = match.strip() - - try: - if img_src.startswith('data:image'): - header, encoded = img_src.split(',', 1) - mime_type = header.split(';')[0].split(':')[1] - image_bytes = base64.b64decode(encoded) - image_parts.append(genai.types.Part(inline_data=genai.types.Blob(mime_type=mime_type, data=image_bytes))) - - elif img_src.startswith('http://') or img_src.startswith('https://'): - response = requests.get(img_src, timeout=10) # 10 seconds timeout - response.raise_for_status() - - image_bytes = response.content - mime_type = response.headers.get('Content-Type', 'application/octet-stream') - - if not mime_type.startswith('image/'): - CustomUserWarning(f"URL content type '{mime_type}' does not appear to be an image for: {img_src}. Attempting to use anyway.") - - image_parts.append(genai.types.Part(inline_data=genai.types.Blob(mime_type=mime_type, data=image_bytes))) - - elif img_src.startswith('frames:'): - temp_path = img_src.replace('frames:', '') - parts = temp_path.split(':', 1) - if len(parts) != 2: - CustomUserWarning(f"Invalid 'frames:' format: {img_src}") - continue - max_used_frames_str, actual_path = parts - try: - max_used_frames = int(max_used_frames_str) - except ValueError: - CustomUserWarning(f"Invalid max_frames number in 'frames:' format: {img_src}") - continue - - frame_buffers, ext = encode_media_frames(actual_path) - - mime_type = f'image/{ext.lower()}' if ext else 'application/octet-stream' - if ext and ext.lower() == 'jpg': - mime_type = 'image/jpeg' - - if not frame_buffers: - CustomUserWarning(f"encode_media_frames returned no frames for: {actual_path}") - continue - - step = max(1, len(frame_buffers) // 50) - indices = list(range(0, len(frame_buffers), step))[:max_used_frames] - - for i_idx in indices: - if i_idx < len(frame_buffers): - image_bytes = frame_buffers[i_idx] - image_parts.append(genai.types.Part(inline_data=genai.types.Blob(mime_type=mime_type, data=image_bytes))) - - else: - # Handle local file paths - local_file_path = Path(img_src) - if not local_file_path.is_file(): - CustomUserWarning(f"Local image file not found: {img_src}") - continue - - image_bytes = local_file_path.read_bytes() - mime_type, _ = mimetypes.guess_type(local_file_path) - if mime_type is None: # Fallback MIME type determination - file_ext = local_file_path.suffix.lower().lstrip('.') - if file_ext == 'jpg': mime_type = 'image/jpeg' - elif file_ext == 'png': mime_type = 'image/png' - elif file_ext == 'gif': mime_type = 'image/gif' - elif file_ext == 'webp': mime_type = 'image/webp' - else: mime_type = 'application/octet-stream' - - image_parts.append(genai.types.Part(inline_data=genai.types.Blob(mime_type=mime_type, data=image_bytes))) - - except Exception as e: - CustomUserWarning(f"Failed to process image source '{img_src}'. Error: {str(e)}", raise_with=ValueError) - - return image_parts - - def _handle_video_content(self, content: str): - """Handle video content by uploading to Gemini""" - try: - pattern = r'<>' - matches = re.findall(pattern, content) - if not matches: - return None - - video_path = matches[0].strip() - if video_path.startswith('http'): - CustomUserWarning("URL videos not yet supported for Gemini") - return None - else: - # Upload local video - uploaded_file = genai.upload_file(video_path) - return uploaded_file - except Exception as e: - CustomUserWarning(f"Failed to process video: {e}") - return None - - def _handle_audio_content(self, content: str): - """Handle audio content by uploading to Gemini""" - try: - pattern = r'<>' - matches = re.findall(pattern, content) - if not matches: - return None - - audio_path = matches[0].strip() - if audio_path.startswith('http'): - CustomUserWarning("URL audio not yet supported for Gemini") - return None - else: - # Upload local audio - uploaded_file = genai.upload_file(audio_path) - return uploaded_file - except Exception as e: - CustomUserWarning(f"Failed to process audio: {e}") - return None - - def _remove_media_patterns(self, text: str) -> str: - """Remove media pattern markers from text""" - patterns = [ - r'<>', - r'<>', - r'<>', - r'<>' - ] - - for pattern in patterns: - text = re.sub(pattern, '', text) - - return text - - def _process_multimodal_content(self, processed_input_str: str) -> list: - """Process all multimodal content and return list of media files""" - media_content = [] - - # Process document content - if '< dict[str, str]: - """Collect thinking and text content from response""" - thinking_content = "" - text_content = "" - - if hasattr(res, 'candidates') and res.candidates: - candidate = res.candidates[0] - if hasattr(candidate, 'content') and candidate.content: - for part in candidate.content.parts: - if hasattr(part, 'text') and part.text: - if hasattr(part, 'thought') and part.thought: - thinking_content += part.text - else: - text_content += part.text - - return { - "thinking": thinking_content, - "text": text_content - } - - def forward(self, argument): - kwargs = argument.kwargs - system, prompt = argument.prop.prepared_input - payload = self._prepare_request_payload(argument) - except_remedy = kwargs.get('except_remedy') - - contents = [] - for msg in prompt: - role = msg['role'] - parts_list = msg['content'] - contents.append(types.Content(role=role, parts=parts_list)) - - try: - generation_config = types.GenerateContentConfig( - max_output_tokens=payload.get('max_output_tokens'), - temperature=payload.get('temperature', 1.0), - top_p=payload.get('top_p', 0.95), - top_k=payload.get('top_k', 40), - stop_sequences=payload.get('stop_sequences'), - response_mime_type=payload.get('response_mime_type', 'text/plain'), - ) - - if payload.get('system_instruction'): - generation_config.system_instruction = payload['system_instruction'] - - if payload.get('thinking_config'): - generation_config.thinking_config = payload['thinking_config'] - - if payload.get('tools'): - generation_config.tools = payload['tools'] - generation_config.automatic_function_calling=payload['automatic_function_calling'] - - res = self.client.models.generate_content( - model=kwargs.get('model', self.model), - contents=contents, - config=generation_config - ) - - except Exception as e: - if self.api_key is None or self.api_key == '': - msg = 'Google API key is not set. Please set it in the config file or pass it as an argument to the command method.' - logging.error(msg) - if self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] is None or self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] == '': - CustomUserWarning(msg, raise_with=ValueError) - self.api_key = self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] - genai.configure(api_key=self.api_key) - - if except_remedy is not None: - res = except_remedy(self, e, self.client.generate_content, argument) - else: - CustomUserWarning(f"Error during generation: {str(e)}", raise_with=ValueError) - - metadata = {'raw_output': res} - if payload.get('tools'): - metadata = self._process_function_calls(res, metadata) - - if kwargs.get('raw_output', False): - return [res], metadata - - output = self._collect_response(res) - - if output['thinking']: - metadata['thinking'] = output['thinking'] - - processed_text = output['text'] - if argument.prop.response_format: - # Safely remove JSON markdown formatting if present - processed_text = processed_text.replace('```json', '').replace('```', '') - - return [processed_text], metadata - - def _process_function_calls(self, res, metadata): - hit = False - if hasattr(res, 'candidates') and res.candidates: - candidate = res.candidates[0] - if hasattr(candidate, 'content') and candidate.content: - for part in candidate.content.parts: - if hasattr(part, 'function_call') and part.function_call: - if hit: - CustomUserWarning("Multiple function calls detected in the response but only the first one will be processed.") - break - func_call = part.function_call - metadata['function_call'] = { - 'name': func_call.name, - 'arguments': func_call.args - } - hit = True - return metadata - - def _prepare_raw_input(self, argument): - if not argument.prop.processed_input: - CustomUserWarning('Need to provide a prompt instruction to the engine if `raw_input` is enabled!', raise_with=ValueError) - - raw_prompt_data = argument.prop.processed_input - messages_for_api = [] - system_instruction = None - - if isinstance(raw_prompt_data, str): - normalized_prompts = [{'role': 'user', 'content': raw_prompt_data}] - elif isinstance(raw_prompt_data, dict): - normalized_prompts = [raw_prompt_data] - elif isinstance(raw_prompt_data, list): - for item in raw_prompt_data: - if not isinstance(item, dict): - CustomUserWarning(f"Invalid item in raw_input list: {item}. Expected dict.", raise_with=ValueError) - normalized_prompts = raw_prompt_data - else: - CustomUserWarning(f"Unsupported type for raw_input: {type(raw_prompt_data)}. Expected str, dict, or list of dicts.", raise_with=ValueError) - - temp_non_system_messages = [] - for msg in normalized_prompts: - role = msg.get('role') - content = msg.get('content') - - if role is None or content is None: - CustomUserWarning(f"Message in raw_input is missing 'role' or 'content': {msg}", raise_with=ValueError) - if not isinstance(content, str): - CustomUserWarning(f"Message content for role '{role}' in raw_input must be a string. Found type: {type(content)} for content: {content}", raise_with=ValueError) - if role == 'system': - if system_instruction is not None: - CustomUserWarning('Only one system instruction is allowed in raw_input mode!', raise_with=ValueError) - system_instruction = content - else: - temp_non_system_messages.append({'role': role, 'content': content}) - - for msg in temp_non_system_messages: - content_str = str(msg.get('content', '')) - - current_message_api_parts: list[types.Part] = [] - - image_api_parts = self._handle_image_content(content_str) - if image_api_parts: - current_message_api_parts.extend(image_api_parts) - - text_only_content = self._remove_media_patterns(content_str) - if text_only_content: - current_message_api_parts.append(types.Part(text=text_only_content)) - - if current_message_api_parts: - messages_for_api.append({ - 'role': msg['role'], - 'content': current_message_api_parts - }) - - return system_instruction, messages_for_api - - def prepare(self, argument): - #@NOTE: OpenAI compatibility at high level - if argument.prop.raw_input: - argument.prop.prepared_input = self._prepare_raw_input(argument) - return - - _non_verbose_output = """\nYou do not output anything else, like verbose preambles or post explanation, such as "Sure, let me...", "Hope that was helpful...", "Yes, I can help you with that...", etc. Consider well formatted output, e.g. for sentences use punctuation, spaces etc. or for code use indentation, etc. Never add meta instructions information to your output!\n\n""" - - user_content = "" - system_content = "" - - if argument.prop.suppress_verbose_output: - system_content += _non_verbose_output - system_content = f'{system_content}\n' if system_content and len(system_content) > 0 else '' - - if argument.prop.response_format: - _rsp_fmt = argument.prop.response_format - assert _rsp_fmt.get('type') is not None, 'Response format type is required!' - if _rsp_fmt["type"] == "json_object": - system_content += f'\nYou are a helpful assistant designed to output JSON.\n\n' - - ref = argument.prop.instance - static_ctxt, dyn_ctxt = ref.global_context - if len(static_ctxt) > 0: - system_content += f"\n{static_ctxt}\n\n" - - if len(dyn_ctxt) > 0: - system_content += f"\n{dyn_ctxt}\n\n" - - payload = argument.prop.payload - if argument.prop.payload: - system_content += f"\n{str(payload)}\n\n" - - examples: list[str] = argument.prop.examples - if examples and len(examples) > 0: - system_content += f"\n{str(examples)}\n\n" - - # Handle multimodal content - processed_input_str = str(argument.prop.processed_input) - media_content = self._process_multimodal_content(processed_input_str) - - if argument.prop.prompt is not None and len(argument.prop.prompt) > 0: - val = str(argument.prop.prompt) - val = self._remove_media_patterns(val) - system_content += f"\n{val}\n\n" - - suffix = str(argument.prop.processed_input) - suffix = self._remove_media_patterns(suffix) - user_content += f"{suffix}" - - if argument.prop.template_suffix: - system_content += f' You will only generate content for the placeholder `{str(argument.prop.template_suffix)}` following the instructions and the provided context information.\n\n' - - # Handle self-prompting - if argument.prop.instance._kwargs.get('self_prompt', False) or argument.prop.self_prompt: - self_prompter = SelfPrompt() - - res = self_prompter( - {'user': user_content, 'system': system_content}, - max_tokens=argument.kwargs.get('max_tokens', self.max_response_tokens), - thinking=argument.kwargs.get('thinking', None), - ) - if res is None: - CustomUserWarning("Self-prompting failed!", raise_with=ValueError) - - user_content = res['user'] - system_content = res['system'] - - all_user_content = [] - all_user_content.extend(media_content) # - if user_content.strip(): - all_user_content.append(genai.types.Part(text=user_content.strip())) - - if not all_user_content: - all_user_content = [genai.types.Part(text="N/A")] - - user_prompt = {'role': 'user', 'content': all_user_content} - - argument.prop.prepared_input = (system_content, [user_prompt]) - - def _prepare_request_payload(self, argument): - kwargs = argument.kwargs - - payload = { - "max_output_tokens": kwargs.get('max_tokens', self.max_response_tokens), - "temperature": kwargs.get('temperature', 1.0), - "top_p": kwargs.get('top_p', 0.95), - "top_k": kwargs.get('top_k', 40), - "stop_sequences": kwargs.get('stop', None), - "stream": kwargs.get('stream', False), - } - - system, _ = argument.prop.prepared_input - if system and system.strip(): - payload['system_instruction'] = system.strip() - - thinking_arg = kwargs.get('thinking', None) - if thinking_arg and isinstance(thinking_arg, dict): - thinking_budget = thinking_arg.get("thinking_budget", 1024) - payload['thinking_config'] = types.ThinkingConfig(include_thoughts=True, thinking_budget=thinking_budget) - - response_format = kwargs.get('response_format', None) - if response_format and response_format.get('type') == 'json_object': - payload['response_mime_type'] = 'application/json' - - tools = kwargs.get('tools') - if tools: - payload['tools'] = self._convert_tools_format(tools) - payload['automatic_function_calling'] = types.AutomaticFunctionCallingConfig( - disable=kwargs.get('automatic_function_calling', True) - ) - - return payload - - def _convert_tools_format(self, tools): - if tools is None: - return None - - if not isinstance(tools, list): - tools = [tools] - - processed_tools = [] - for tool_item in tools: - if callable(tool_item): - processed_tools.append(tool_item) - elif isinstance(tool_item, types.FunctionDeclaration): - processed_tools.append(types.Tool(function_declarations=[tool_item])) - else: - CustomUserWarning(f"Ignoring invalid tool format. Expected a callable, google.genai.types.Tool, or google.genai.types.FunctionDeclaration: {tool_item}") - - if not processed_tools: - return None - - return processed_tools diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_huggingface.py b/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_huggingface.py deleted file mode 100644 index 827761f364642b060ead2a67c76b95d52749482f..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_huggingface.py +++ /dev/null @@ -1,186 +0,0 @@ -import json -import logging -import re -from copy import deepcopy -from typing import List, Optional - -import requests - -from ....utils import CustomUserWarning -from ...base import Engine -from ...settings import SYMAI_CONFIG, SYMSERVER_CONFIG - -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - - -class HFTokenizer: - _server_endpoint = f"http://{SYMSERVER_CONFIG.get('host')}:{SYMSERVER_CONFIG.get('port')}" - - @staticmethod - def encode(text: str, add_special_tokens: bool = False) -> List[int]: - res = requests.post(f"{HFTokenizer._server_endpoint}/tokenize", json={ - "input": text, - "add_special_tokens": add_special_tokens, - }) - - if res.status_code != 200: - CustomUserWarning(f"Request failed with status code: {res.status_code}", raise_with=ValueError) - - res = res.json() - - return res['tokens'] - - @staticmethod - def decode(tokens: List[int], skip_special_tokens: bool = True) -> str: - res = requests.post(f"{HFTokenizer._server_endpoint}/detokenize", json={ - "tokens": tokens, - "skip_special_tokens": skip_special_tokens, - }) - - if res.status_code != 200: - CustomUserWarning(f"Request failed with status code: {res.status_code}", raise_with=ValueError) - - res = res.json() - - return res['text'] - - -class HFEngine(Engine): - def __init__(self, model: Optional[str] = None): - super().__init__() - self.config = deepcopy(SYMAI_CONFIG) - # In case we use EngineRepository.register to inject the api_key and model => dynamically change the engine at runtime - if model is not None: - self.config['NEUROSYMBOLIC_ENGINE_MODEL'] = model - if self.id() != 'neurosymbolic': - return - if not SYMSERVER_CONFIG.get('online'): - CustomUserWarning('You are using the huggingface engine, but the server endpoint is not started. Please start the server with `symserver [--args]` or run `symserver --help` to see the available options for this engine.', raise_with=ValueError) - self.server_endpoint = f"http://{SYMSERVER_CONFIG.get('host')}:{SYMSERVER_CONFIG.get('port')}" - self.tokenizer = HFTokenizer # backwards compatibility with how we handle tokenization, i.e. self.tokenizer().encode(...) - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config.get('NEUROSYMBOLIC_ENGINE_MODEL') and self.config.get('NEUROSYMBOLIC_ENGINE_MODEL').startswith('huggingface'): - return 'neurosymbolic' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'NEUROSYMBOLIC_ENGINE_MODEL' in kwargs: - self.model = kwargs['NEUROSYMBOLIC_ENGINE_MODEL'] - if 'seed' in kwargs: - self.seed = kwargs['seed'] - if 'except_remedy' in kwargs: - self.except_remedy = kwargs['except_remedy'] - - def compute_required_tokens(self, messages) -> int: - CustomUserWarning('Not implemented for HFEngine. Please use the tokenizer directly to compute tokens.', raise_with=NotImplementedError) - def compute_remaining_tokens(self, prompts: list) -> int: - CustomUserWarning('Not implemented for HFEngine. Please use the tokenizer directly to compute tokens.', raise_with=NotImplementedError) - def forward(self, argument): - kwargs = argument.kwargs - prompts = argument.prop.prepared_input - - stop = kwargs.get('stop') - seed = kwargs.get('seed') - temperature = kwargs.get('temperature', 1.) - top_p = kwargs.get('top_p', 1.) - top_k = kwargs.get('top_k', 50) - max_tokens = kwargs.get('max_tokens', 2048) - max_tokens_forcing = kwargs.get('max_tokens_forcing') - logprobs = kwargs.get('logprobs', True) - do_sample = kwargs.get('do_sample', True) - num_beams = kwargs.get('num_beams', 1) - num_beam_groups = kwargs.get('num_beam_groups', 1) - eos_token_id = kwargs.get('eos_token_id') - except_remedy = kwargs.get('except_remedy') - - try: - res = requests.post(f"{self.server_endpoint}/chat", json={ - "messages": prompts, - "temperature": temperature, - "top_p": top_p, - "stop": stop, - "seed": seed, - "max_tokens": max_tokens, - "max_tokens_forcing": max_tokens_forcing, - "top_k": top_k, - "logprobs": logprobs, - "do_sample": do_sample, - "num_beams": num_beams, - "num_beam_groups": num_beam_groups, - "eos_token_id": eos_token_id, - }) - - if res.status_code != 200: - CustomUserWarning(f"Request failed with status code: {res.status_code}", raise_with=ValueError) - - res = res.json() - - except Exception as e: - if except_remedy is not None: - res = except_remedy(self, e, argument) - else: - CustomUserWarning(f"Request failed with exception: {str(e)}", raise_with=ValueError) - - metadata = {'raw_output': res} - - rsp = [r['message']['content'] for r in res['choices']] - output = rsp if isinstance(prompts, list) else rsp[0] - return output, metadata - - def _prepare_raw_input(self, argument): - if not argument.prop.processed_input: - CustomUserWarning('Need to provide a prompt instruction to the engine if raw_input is enabled.', raise_with=ValueError) - value = argument.prop.processed_input - if type(value) != list: - if type(value) != dict: - value = {'role': 'user', 'content': str(value)} - value = [value] - return value - - def prepare(self, argument): - if argument.prop.raw_input: - argument.prop.prepared_input = self._prepare_raw_input(argument) - return - - _non_verbose_output = """\n You will NOT output verbose preambles or post explanation, such as "Sure, let me...", "Hope that was helpful...", "Yes, I can help you with that...", etc. You will consider well formatted output, e.g. for sentences you will use punctuation, spaces, etc. or for code indentation, etc.\n""" - - #@TODO: Non-trivial how to handle user/system/assistant roles; - user = "" - - if argument.prop.suppress_verbose_output: - user += _non_verbose_output - user = f'{user}\n' if user and len(user) > 0 else '' - - ref = argument.prop.instance - static_ctxt, dyn_ctxt = ref.global_context - if len(static_ctxt) > 0: - user += f"\n{static_ctxt}\n\n" - - if len(dyn_ctxt) > 0: - user += f"\n{dyn_ctxt}\n\n" - - payload = argument.prop.payload - if argument.prop.payload: - user += f"\n{str(payload)}\n\n" - - examples: List[str] = argument.prop.examples - if examples and len(examples) > 0: - user += f"\n{str(examples)}\n\n" - - if argument.prop.prompt is not None and len(argument.prop.prompt) > 0: - user += f"\n{str(argument.prop.prompt)}\n\n" - - if argument.prop.template_suffix: - user += f" You will only generate content for the placeholder `{str(argument.prop.template_suffix)}` following the instructions and the provided context information.\n\n" - - user += str(argument.prop.processed_input) - - argument.prop.prepared_input = [ - { "role": "user", "content": user }, - ] diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_llama_cpp.py b/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_llama_cpp.py deleted file mode 100644 index 2050de97d08ca752c0816c2189e1550c7ebc5f95..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_llama_cpp.py +++ /dev/null @@ -1,261 +0,0 @@ -import asyncio -import json -import logging -from copy import deepcopy - -import aiohttp -import httpx -import nest_asyncio -import requests - -from ....core import Argument -from ....core_ext import retry -from ....utils import CustomUserWarning -from ...base import Engine -from ...settings import SYMAI_CONFIG, SYMSERVER_CONFIG - -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - - -class LlamaCppTokenizer: - _server_endpoint = f"http://{SYMSERVER_CONFIG.get('--host')}:{SYMSERVER_CONFIG.get('--port')}" - - @staticmethod - async def _encode(text: str) -> list[int]: - async with aiohttp.ClientSession() as session: - async with session.post(f"{LlamaCppTokenizer._server_endpoint}/extras/tokenize", json={ - "input": text, - }) as res: - if res.status != 200: - CustomUserWarning(f"Request failed with status code: {res.status}", raise_with=ValueError) - res = await res.json() - return res['tokens'] - - @staticmethod - def encode(text: str) -> list[int]: - try: - loop = asyncio.get_event_loop() - except RuntimeError: - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - return loop.run_until_complete(LlamaCppTokenizer._encode(text)) - - @staticmethod - async def _decode(tokens: list[int]) -> str: - async with aiohttp.ClientSession() as session: - async with session.post(f"{LlamaCppTokenizer._server_endpoint}/extras/detokenize", json={ - "tokens": tokens, - }) as res: - if res.status != 200: - CustomUserWarning(f"Request failed with status code: {res.status}", raise_with=ValueError) - res = await res.json() - return res['text'] - - @staticmethod - def decode(tokens: list[int]) -> str: - try: - loop = asyncio.get_event_loop() - except RuntimeError: - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - return loop.run_until_complete(LlamaCppTokenizer._decode(tokens)) - - -class LlamaCppEngine(Engine): - _retry_params = { - 'tries': 5, - 'delay': 2, - 'max_delay': 60, - 'backoff': 2, - 'jitter': (1, 5), - 'graceful': True - } - _timeout_params = { - 'read': None, - 'connect': None, - } - def __init__( - self, - model: str | None = None, - retry_params: dict = _retry_params, - timeout_params: dict = _timeout_params, - ): - super().__init__() - self.config = deepcopy(SYMAI_CONFIG) - # In case we use EngineRepository.register to inject the api_key and model => dynamically change the engine at runtime - if model is not None: - self.config['NEUROSYMBOLIC_ENGINE_MODEL'] = model - if self.id() != 'neurosymbolic': - return - if not SYMSERVER_CONFIG.get('online'): - CustomUserWarning('You are using the llama.cpp engine, but the server endpoint is not started. Please start the server with `symserver [--args]` or run `symserver --help` to see the available options for this engine.', raise_with=ValueError) - self.server_endpoint = f"http://{SYMSERVER_CONFIG.get('--host')}:{SYMSERVER_CONFIG.get('--port')}" - self.tokenizer = LlamaCppTokenizer # backwards compatibility with how we handle tokenization, i.e. self.tokenizer().encode(...) - self.timeout_params = self._validate_timeout_params(timeout_params) - self.retry_params = self._validate_retry_params(retry_params) - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config.get('NEUROSYMBOLIC_ENGINE_MODEL') and self.config.get('NEUROSYMBOLIC_ENGINE_MODEL').startswith('llama'): - return 'neurosymbolic' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'NEUROSYMBOLIC_ENGINE_MODEL' in kwargs: - self.model = kwargs['NEUROSYMBOLIC_ENGINE_MODEL'] - if 'seed' in kwargs: - self.seed = kwargs['seed'] - if 'except_remedy' in kwargs: - self.except_remedy = kwargs['except_remedy'] - - def compute_required_tokens(self, messages) -> int: - #@TODO: quite non-trivial how to handle this with the llama.cpp server - CustomUserWarning('Not implemented for llama.cpp!', raise_with=NotImplementedError) - - def compute_remaining_tokens(self, prompts: list) -> int: - #@TODO: quite non-trivial how to handle this with the llama.cpp server - CustomUserWarning('Not implemented for llama.cpp!', raise_with=NotImplementedError) - - def _validate_timeout_params(self, timeout_params): - if not isinstance(timeout_params, dict): - CustomUserWarning("timeout_params must be a dictionary", raise_with=ValueError) - assert all(key in timeout_params for key in ['read', 'connect']), "Available keys: ['read', 'connect']" - return timeout_params - - def _validate_retry_params(self, retry_params): - if not isinstance(retry_params, dict): - CustomUserWarning("retry_params must be a dictionary", raise_with=ValueError) - assert all(key in retry_params for key in ['tries', 'delay', 'max_delay', 'backoff', 'jitter', 'graceful']), "Available keys: ['tries', 'delay', 'max_delay', 'backoff', 'jitter', 'graceful']" - return retry_params - - @staticmethod - def _get_event_loop() -> asyncio.AbstractEventLoop: - """Gets or creates an event loop.""" - try: - current_loop = asyncio.get_event_loop() - if current_loop.is_closed(): - CustomUserWarning("Event loop is closed.", raise_with=RuntimeError) - return current_loop - except RuntimeError: - new_loop = asyncio.new_event_loop() - asyncio.set_event_loop(new_loop) - return new_loop - - def _prepare_request_payload(self, argument: Argument) -> dict: - """Prepares the request payload from the argument.""" - kwargs = argument.kwargs - return { - "messages": argument.prop.prepared_input, - "temperature": kwargs.get('temperature', 0.6), - "frequency_penalty": kwargs.get('frequency_penalty', 0), - "presence_penalty": kwargs.get('presence_penalty', 0), - "top_p": kwargs.get('top_p', 0.95), - "min_p": kwargs.get('min_p', 0.05), - "stop": kwargs.get('stop'), - "seed": kwargs.get('seed'), - "max_tokens": kwargs.get('max_tokens'), - "top_k": kwargs.get('top_k', 40), - "repeat_penalty": kwargs.get('repeat_penalty', 1), - "logits_bias": kwargs.get('logits_bias'), - "logprobs": kwargs.get('logprobs', False), - "functions": kwargs.get('functions'), - "function_call": kwargs.get('function_call'), - "grammar": kwargs.get('grammar'), - "response_format": kwargs.get('response_format'), - } - - async def _arequest(self, payload: dict) -> dict: - """Makes an async HTTP request to the llama.cpp server.""" - @retry(**self.retry_params) - async def _make_request(): - timeout = aiohttp.ClientTimeout( - sock_connect=self.timeout_params['connect'], - sock_read=self.timeout_params['read'] - ) - async with aiohttp.ClientSession(timeout=timeout) as session: - async with session.post( - f"{self.server_endpoint}/v1/chat/completions", - json=payload - ) as res: - if res.status != 200: - CustomUserWarning(f"Request failed with status code: {res.status}", raise_with=ValueError) - return await res.json() - - return await _make_request() - - def forward(self, argument): - payload = self._prepare_request_payload(argument) - - nest_asyncio.apply() - loop = self._get_event_loop() - - try: - res = loop.run_until_complete(self._arequest(payload)) - except Exception as e: - CustomUserWarning(f"Request failed with error: {str(e)}", raise_with=ValueError) - - metadata = {'raw_output': res} - - output = [r['message']['content'] for r in res['choices']] - output = output if isinstance(argument.prop.prepared_input, list) else output[0] - - return output, metadata - - def _prepare_raw_input(self, argument): - if not argument.prop.processed_input: - CustomUserWarning('Need to provide a prompt instruction to the engine if raw_input is enabled.', raise_with=ValueError) - value = argument.prop.processed_input - if type(value) != list: - if type(value) != dict: - value = {'role': 'user', 'content': str(value)} - value = [value] - return value - - def prepare(self, argument): - if argument.prop.raw_input: - argument.prop.prepared_input = self._prepare_raw_input(argument) - return - - _non_verbose_output = """\n You will NOT output verbose preambles or post explanation, such as "Sure, let me...", "Hope that was helpful...", "Yes, I can help you with that...", etc. You will consider well formatted output, e.g. for sentences you will use punctuation, spaces, etc. or for code indentation, etc.\n""" - - #@TODO: Non-trivial how to handle user/system/assistant roles; - # For instance Mixtral-8x7B can't use the system role with llama.cpp while other models can, or Mixtral-8x22B expects the conversation roles must - # alternate user/assistant/user/assistant/..., so how to handle this? - # For now just use the user, as one can rephrase the system from the user perspective. - user: str = "" - - if argument.prop.suppress_verbose_output: - user += _non_verbose_output - user = f'{user}\n' if user and len(user) > 0 else '' - - ref = argument.prop.instance - static_ctxt, dyn_ctxt = ref.global_context - if len(static_ctxt) > 0: - user += f"\n{static_ctxt}\n\n" - - if len(dyn_ctxt) > 0: - user += f"\n{dyn_ctxt}\n\n" - - payload = argument.prop.payload - if argument.prop.payload: - user += f"\n{str(payload)}\n\n" - - examples: list[str] = argument.prop.examples - if examples and len(examples) > 0: - user += f"\n{str(examples)}\n\n" - - if argument.prop.prompt is not None and len(argument.prop.prompt) > 0: - user += f"\n{str(argument.prop.prompt)}\n\n" - - if argument.prop.template_suffix: - user += f" You will only generate content for the placeholder `{str(argument.prop.template_suffix)}` following the instructions and the provided context information.\n\n" - - user += str(argument.prop.processed_input) - - argument.prop.prepared_input = [ - { "role": "user", "content": user }, - ] diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_openai_gptX_chat.py b/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_openai_gptX_chat.py deleted file mode 100644 index b9cfbcd4c1bb93ac80e7d9c15df20acf9d7204c6..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_openai_gptX_chat.py +++ /dev/null @@ -1,506 +0,0 @@ -import json -import logging -import re -from copy import deepcopy -from typing import List, Optional - -import openai -import tiktoken - -from ....components import SelfPrompt -from ....misc.console import ConsoleStyle -from ....symbol import Symbol -from ....utils import CustomUserWarning, encode_media_frames -from ...base import Engine -from ...mixin.openai import OpenAIMixin -from ...settings import SYMAI_CONFIG - -logging.getLogger("openai").setLevel(logging.ERROR) -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - - -class GPTXChatEngine(Engine, OpenAIMixin): - def __init__(self, api_key: Optional[str] = None, model: Optional[str] = None): - super().__init__() - self.config = deepcopy(SYMAI_CONFIG) - # In case we use EngineRepository.register to inject the api_key and model => dynamically change the engine at runtime - if api_key is not None and model is not None: - self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] = api_key - self.config['NEUROSYMBOLIC_ENGINE_MODEL'] = model - if self.id() != 'neurosymbolic': - return # do not initialize if not neurosymbolic; avoids conflict with llama.cpp check in EngineRepository.register_from_package - openai.api_key = self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] - self.model = self.config['NEUROSYMBOLIC_ENGINE_MODEL'] - try: - self.tokenizer = tiktoken.encoding_for_model(self.model) - except Exception as e: - self.tokenizer = tiktoken.get_encoding('o200k_base') - self.max_context_tokens = self.api_max_context_tokens() - self.max_response_tokens = self.api_max_response_tokens() - self.seed = None - self.name = self.__class__.__name__ - - try: - self.client = openai.Client(api_key=openai.api_key) - except Exception as e: - CustomUserWarning(f'Failed to initialize OpenAI client. Please check your OpenAI library version. Caused by: {e}', raise_with=ValueError) - - def id(self) -> str: - if self.config.get('NEUROSYMBOLIC_ENGINE_MODEL') and \ - (self.config.get('NEUROSYMBOLIC_ENGINE_MODEL').startswith('gpt-3.5') or \ - self.config.get('NEUROSYMBOLIC_ENGINE_MODEL').startswith('gpt-4') or \ - self.config.get('NEUROSYMBOLIC_ENGINE_MODEL').startswith('chatgpt-4o') or \ - self.config.get('NEUROSYMBOLIC_ENGINE_MODEL').startswith('gpt-4.1')): - return 'neurosymbolic' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'NEUROSYMBOLIC_ENGINE_API_KEY' in kwargs: - openai.api_key = kwargs['NEUROSYMBOLIC_ENGINE_API_KEY'] - if 'NEUROSYMBOLIC_ENGINE_MODEL' in kwargs: - self.model = kwargs['NEUROSYMBOLIC_ENGINE_MODEL'] - if 'seed' in kwargs: - self.seed = kwargs['seed'] - - def compute_required_tokens(self, messages): - """Return the number of tokens used by a list of messages.""" - - if self.model in { - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-16k-0613", - "gpt-4-1106-preview", - "gpt-4-0314", - "gpt-4-32k-0314", - "gpt-4-0613", - "gpt-4-32k-0613", - "gpt-4-turbo", - "gpt-4o", - "gpt-4o-2024-11-20", - "gpt-4o-mini", - "chatgpt-4o-latest", - "gpt-4.1", - "gpt-4.1-mini", - "gpt-4.1-nano" - }: - tokens_per_message = 3 - tokens_per_name = 1 - elif self.model == "gpt-3.5-turbo-0301": - tokens_per_message = 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n - tokens_per_name = -1 # if there's a name, the role is omitted - elif self.model == "gpt-3.5-turbo": - CustomUserWarning("Warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.") - tokens_per_message = 3 - tokens_per_name = 1 - self.tokenizer = tiktoken.encoding_for_model("gpt-3.5-turbo-0613") - elif self.model == "gpt-4": - tokens_per_message = 3 - tokens_per_name = 1 - CustomUserWarning("Warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.") - self.tokenizer = tiktoken.encoding_for_model("gpt-4-0613") - else: - CustomUserWarning( - f"""num_tokens_from_messages() is not implemented for model {self.model}. See https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken for information on how messages are converted to tokens.""", - raise_with=NotImplementedError - ) - - num_tokens = 0 - for message in messages: - num_tokens += tokens_per_message - for key, value in message.items(): - if type(value) == str: - num_tokens += len(self.tokenizer.encode(value, disallowed_special=())) - else: - for v in value: - if v['type'] == 'text': - num_tokens += len(self.tokenizer.encode(v['text'], disallowed_special=())) - if key == "name": - num_tokens += tokens_per_name - num_tokens += 3 # every reply is primed with <|start|>assistant<|message|> - return num_tokens - - def compute_remaining_tokens(self, prompts: list) -> int: - val = self.compute_required_tokens(prompts) - return min(self.max_context_tokens - val, self.max_response_tokens) - - def _handle_image_content(self, content: str) -> list: - """Handle image content by processing vision patterns and returning image file data.""" - def extract_pattern(text): - pattern = r'<>' - return re.findall(pattern, text) - - image_files = [] - # pre-process prompt if contains image url - if (self.model == 'gpt-4-vision-preview' or \ - self.model == 'gpt-4-turbo-2024-04-09' or \ - self.model == 'gpt-4-turbo' or \ - self.model == 'gpt-4o' or \ - self.model == 'gpt-4o-mini' or \ - self.model == 'chatgpt-4o-latest' or \ - self.model == 'gpt-4.1' or \ - self.model == 'gpt-4.1-mini' or \ - self.model == 'gpt-4.1-nano') \ - and '< max_frames_spacing: - CustomUserWarning(f"Invalid max_used_frames value: {max_used_frames}. Expected value between 1 and {max_frames_spacing}", raise_with=ValueError) - buffer, ext = encode_media_frames(img_) - if len(buffer) > 1: - step = len(buffer) // max_frames_spacing # max frames spacing - frames = [] - indices = list(range(0, len(buffer), step))[:max_used_frames] - for i in indices: - frames.append(f"data:image/{ext};base64,{buffer[i]}") - image_files.extend(frames) - elif len(buffer) == 1: - image_files.append(f"data:image/{ext};base64,{buffer[0]}") - else: - print('No frames found or error in encoding frames') - return image_files - - def _remove_vision_pattern(self, text: str) -> str: - """Remove vision patterns from text.""" - pattern = r'<>' - return re.sub(pattern, '', text) - - def truncate(self, prompts: list[dict], truncation_percentage: float | None, truncation_type: str) -> list[dict]: - """Main truncation method""" - def _slice_tokens(tokens, new_len, truncation_type): - """Slice tokens based on truncation type""" - new_len = max(100, new_len) # Ensure minimum token length - return tokens[-new_len:] if truncation_type == 'head' else tokens[:new_len] # else 'tail' - - if len(prompts) != 2 and all(prompt['role'] in ['system', 'user'] for prompt in prompts): - # Only support system and user prompts - CustomUserWarning(f"Token truncation currently supports only two messages, from 'user' and 'system' (got {len(prompts)}). Returning original prompts.") - return prompts - - if truncation_percentage is None: - # Calculate smart truncation percentage based on model's max messages and completion tokens - truncation_percentage = (self.max_context_tokens - self.max_response_tokens) / self.max_context_tokens - - system_prompt = prompts[0] - user_prompt = prompts[1] - - # Get token counts - system_tokens = Symbol(system_prompt['content']).tokens - user_tokens = [] - - if isinstance(user_prompt['content'], str): - # Default input format - user_tokens.extend(Symbol(user_prompt['content']).tokens) - elif isinstance(user_prompt['content'], list): - for content_item in user_prompt['content']: - # Image input format - if isinstance(content_item, dict): - if content_item.get('type') == 'text': - user_tokens.extend(Symbol(content_item['text']).tokens) - else: - # Image content; return original since not supported - return prompts - else: - # Unknown input format - return ValueError(f"Invalid content type: {type(content_item)}. Format input according to the documentation. See https://platform.openai.com/docs/api-reference/chat/create?lang=python") - else: - # Unknown input format - CustomUserWarning(f"Unknown content type: {type(user_prompt['content'])}. Format input according to the documentation. See https://platform.openai.com/docs/api-reference/chat/create?lang=python", raise_with=ValueError) - - system_token_count = len(system_tokens) - user_token_count = len(user_tokens) - artifacts = self.compute_required_tokens(prompts) - (system_token_count + user_token_count) - assert artifacts >= 0, f"Artifacts count is negative: {artifacts}! Report bug!" - total_tokens = system_token_count + user_token_count + artifacts - - # Calculate maximum allowed tokens - max_prompt_tokens = int(self.max_context_tokens * truncation_percentage) - - # If total is within limit, return original - if total_tokens <= max_prompt_tokens: - return prompts - - CustomUserWarning( - f"Executing {truncation_type} truncation to fit within {max_prompt_tokens} tokens. " - f"Combined prompts ({total_tokens} tokens) exceed maximum allowed tokens " - f"of {max_prompt_tokens} ({truncation_percentage*100:.1f}% of context). " - f"You can control this behavior by setting 'truncation_percentage' (current: {truncation_percentage:.2f}) " - f"and 'truncation_type' (current: '{truncation_type}') parameters. " - f"Set 'truncation_percentage=1.0' to deactivate truncation (will fail if exceeding context window). " - f"Choose 'truncation_type' as 'head' to keep the end of prompts or 'tail' to keep the beginning." - ) - # Case 1: Only user prompt exceeds - if user_token_count > max_prompt_tokens/2 and system_token_count <= max_prompt_tokens/2: - new_user_len = max_prompt_tokens - system_token_count - new_user_tokens = _slice_tokens(user_tokens, new_user_len, truncation_type) - return [ - {'role': 'system', 'content': self.tokenizer.decode(system_tokens)}, - {'role': 'user', 'content': [{'type': 'text', 'text': self.tokenizer.decode(new_user_tokens)}]} - ] - - # Case 2: Only system prompt exceeds - if system_token_count > max_prompt_tokens/2 and user_token_count <= max_prompt_tokens/2: - new_system_len = max_prompt_tokens - user_token_count - new_system_tokens = _slice_tokens(system_tokens, new_system_len, truncation_type) - return [ - {'role': 'system', 'content': self.tokenizer.decode(new_system_tokens)}, - {'role': 'user', 'content': [{'type': 'text', 'text': self.tokenizer.decode(user_tokens)}]} - ] - - # Case 3: Both exceed - reduce proportionally - system_ratio = system_token_count / total_tokens - user_ratio = user_token_count / total_tokens - - new_system_len = int(max_prompt_tokens * system_ratio) - new_user_len = int(max_prompt_tokens * user_ratio) - distribute_tokens = max_prompt_tokens - new_system_len - new_user_len - new_system_len += distribute_tokens // 2 - new_user_len += distribute_tokens // 2 - - new_system_tokens = _slice_tokens(system_tokens, new_system_len, truncation_type) - new_user_tokens = _slice_tokens(user_tokens, new_user_len, truncation_type) - - return [ - {'role': 'system', 'content': self.tokenizer.decode(new_system_tokens)}, - {'role': 'user', 'content': [{'type': 'text', 'text': self.tokenizer.decode(new_user_tokens)}]} - ] - - def forward(self, argument): - kwargs = argument.kwargs - truncation_percentage = kwargs.get('truncation_percentage', argument.prop.truncation_percentage) - truncation_type = kwargs.get('truncation_type', argument.prop.truncation_type) - messages = self.truncate(argument.prop.prepared_input, truncation_percentage, truncation_type) - payload = self._prepare_request_payload(messages, argument) - except_remedy = kwargs.get('except_remedy') - - try: - res = self.client.chat.completions.create(**payload) - - except Exception as e: - if openai.api_key is None or openai.api_key == '': - msg = 'OpenAI API key is not set. Please set it in the config file or pass it as an argument to the command method.' - logging.error(msg) - if self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] is None or self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] == '': - CustomUserWarning(msg, raise_with=ValueError) - openai.api_key = self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] - - callback = self.client.chat.completions.create - kwargs['model'] = kwargs['model'] if 'model' in kwargs else self.model - - if except_remedy is not None: - res = except_remedy(self, e, callback, argument) - else: - CustomUserWarning('An error occurred while calling the OpenAI API. Please check your API key and model name.', raise_with=ValueError) - - metadata = {'raw_output': res} - if payload.get('tools'): - metadata = self._process_function_calls(res, metadata) - output = [r.message.content for r in res.choices] - - return output, metadata - - def _prepare_raw_input(self, argument): - if not argument.prop.processed_input: - CustomUserWarning('Need to provide a prompt instruction to the engine if raw_input is enabled.', raise_with=ValueError) - value = argument.prop.processed_input - # convert to dict if not already - if type(value) != list: - if type(value) != dict: - value = {'role': 'user', 'content': str(value)} - value = [value] - return value - - def prepare(self, argument): - if argument.prop.raw_input: - argument.prop.prepared_input = self._prepare_raw_input(argument) - return - - _non_verbose_output = """\nYou do not output anything else, like verbose preambles or post explanation, such as "Sure, let me...", "Hope that was helpful...", "Yes, I can help you with that...", etc. Consider well formatted output, e.g. for sentences use punctuation, spaces etc. or for code use indentation, etc. Never add meta instructions information to your output!\n\n""" - user: str = "" - system: str = "" - - if argument.prop.suppress_verbose_output: - system += _non_verbose_output - system = f'{system}\n' if system and len(system) > 0 else '' - - if argument.prop.response_format: - _rsp_fmt = argument.prop.response_format - assert _rsp_fmt.get('type') is not None, 'Expected format `{ "type": "json_object" }`! See https://platform.openai.com/docs/api-reference/chat/create#chat-create-response_format' - if _rsp_fmt["type"] == "json_object": - # OpenAI docs: - # "Important: when using JSON mode, you must also instruct the model - # to produce JSON yourself via a system or user message" - system += f'\nYou are a helpful assistant designed to output JSON.\n\n' - - ref = argument.prop.instance - static_ctxt, dyn_ctxt = ref.global_context - if len(static_ctxt) > 0: - system += f"\n{static_ctxt}\n\n" - - if len(dyn_ctxt) > 0: - system += f"\n{dyn_ctxt}\n\n" - - payload = argument.prop.payload - if argument.prop.payload: - system += f"\n{str(payload)}\n\n" - - examples: List[str] = argument.prop.examples - if examples and len(examples) > 0: - system += f"\n{str(examples)}\n\n" - - image_files = self._handle_image_content(str(argument.prop.processed_input)) - - if argument.prop.prompt is not None and len(argument.prop.prompt) > 0: - val = str(argument.prop.prompt) - if len(image_files) > 0: - val = self._remove_vision_pattern(val) - system += f"\n{val}\n\n" - - suffix: str = str(argument.prop.processed_input) - if len(image_files) > 0: - suffix = self._remove_vision_pattern(suffix) - - user += f"{suffix}" - - if argument.prop.template_suffix: - system += f' You will only generate content for the placeholder `{str(argument.prop.template_suffix)}` following the instructions and the provided context information.\n\n' - - if self.model == 'gpt-4-vision-preview': - images = [{ 'type': 'image', "image_url": { "url": file }} for file in image_files] - user_prompt = { "role": "user", "content": [ - *images, - { 'type': 'text', 'text': user } - ]} - elif self.model == 'gpt-4-turbo-2024-04-09' or \ - self.model == 'gpt-4-turbo' or \ - self.model == 'gpt-4o' or \ - self.model == 'gpt-4o-mini' or \ - self.model == 'chatgpt-4o-latest' or \ - self.model == 'gpt-4.1' or \ - self.model == 'gpt-4.1-mini' or \ - self.model == 'gpt-4.1-nano': - - images = [{ 'type': 'image_url', "image_url": { "url": file }} for file in image_files] - user_prompt = { "role": "user", "content": [ - *images, - { 'type': 'text', 'text': user } - ]} - else: - user_prompt = { "role": "user", "content": user } - - # First check if the `Symbol` instance has the flag set, otherwise check if it was passed as an argument to a method - if argument.prop.instance._kwargs.get('self_prompt', False) or argument.prop.self_prompt: - self_prompter = SelfPrompt() - - res = self_prompter({'user': user, 'system': system}) - if res is None: - CustomUserWarning("Self-prompting failed!", raise_with=ValueError) - - if len(image_files) > 0: - user_prompt = { "role": "user", "content": [ - *images, - { 'type': 'text', 'text': res['user'] } - ]} - else: - user_prompt = { "role": "user", "content": res['user'] } - - system = res['system'] - - argument.prop.prepared_input = [ - { "role": "system", "content": system }, - user_prompt, - ] - - def _process_function_calls(self, res, metadata): - hit = False - if hasattr(res, 'choices') and res.choices: - choice = res.choices[0] - if hasattr(choice, 'message') and choice.message: - if hasattr(choice.message, 'tool_calls') and choice.message.tool_calls: - for tool_call in choice.message.tool_calls: - if hasattr(tool_call, 'function') and tool_call.function: - if hit: - CustomUserWarning("Multiple function calls detected in the response but only the first one will be processed.") - break - try: - args_dict = json.loads(tool_call.function.arguments) - except json.JSONDecodeError: - args_dict = {} - metadata['function_call'] = { - 'name': tool_call.function.name, - 'arguments': args_dict - } - hit = True - return metadata - - def _prepare_request_payload(self, messages, argument): - """Prepares the request payload from the argument.""" - kwargs = argument.kwargs - - max_tokens = kwargs.get('max_tokens', None) - max_completion_tokens = kwargs.get('max_completion_tokens', None) - remaining_tokens = self.compute_remaining_tokens(messages) - - if max_tokens is not None: - CustomUserWarning( - "'max_tokens' is now deprecated in favor of 'max_completion_tokens', and is not compatible with o1 series models. " - "We handle this conversion by default for you for now but we won't in the future. " - "See: https://platform.openai.com/docs/api-reference/chat/create" - ) - if max_tokens > self.max_response_tokens: - CustomUserWarning( - f"Provided 'max_tokens' ({max_tokens}) exceeds max response tokens ({self.max_response_tokens}). " - f"Truncating to {remaining_tokens} to avoid API failure." - ) - kwargs['max_completion_tokens'] = remaining_tokens - else: - kwargs['max_completion_tokens'] = max_tokens - del kwargs['max_tokens'] - - if max_completion_tokens is not None: - if max_completion_tokens > self.max_response_tokens: - CustomUserWarning( - f"Provided 'max_completion_tokens' ({max_completion_tokens}) exceeds max response tokens ({self.max_response_tokens}). " - f"Truncating to {remaining_tokens} to avoid API failure." - ) - kwargs['max_completion_tokens'] = remaining_tokens - - payload = { - "messages": messages, - "model": kwargs.get('model', self.model), - "seed": kwargs.get('seed', self.seed), - "max_completion_tokens": kwargs.get('max_completion_tokens'), - "stop": kwargs.get('stop', ''), - "temperature": kwargs.get('temperature', 1), - "frequency_penalty": kwargs.get('frequency_penalty', 0), - "presence_penalty": kwargs.get('presence_penalty', 0), - "top_p": kwargs.get('top_p', 1), - "n": kwargs.get('n', 1), - "logit_bias": kwargs.get('logit_bias'), - "tools": kwargs.get('tools'), - "tool_choice": kwargs.get('tool_choice'), - "response_format": kwargs.get('response_format'), - "logprobs": kwargs.get('logprobs'), - "top_logprobs": kwargs.get('top_logprobs'), - } - - if self.model == "chatgpt-4o-latest": - del payload['tools'] - del payload['tool_choice'] - - return payload diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_openai_gptX_reasoning.py b/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_openai_gptX_reasoning.py deleted file mode 100644 index ed26260931dbce063b5d382d914257c3b8401cec..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/neurosymbolic/engine_openai_gptX_reasoning.py +++ /dev/null @@ -1,455 +0,0 @@ -import json -import logging -import re -from copy import deepcopy -from typing import List, Optional - -import openai -import tiktoken - -from ....components import SelfPrompt -from ....misc.console import ConsoleStyle -from ....symbol import Symbol -from ....utils import CustomUserWarning, encode_media_frames -from ...base import Engine -from ...mixin.openai import OpenAIMixin -from ...settings import SYMAI_CONFIG - -logging.getLogger("openai").setLevel(logging.ERROR) -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - - -class GPTXReasoningEngine(Engine, OpenAIMixin): - def __init__(self, api_key: Optional[str] = None, model: Optional[str] = None): - super().__init__() - self.config = deepcopy(SYMAI_CONFIG) - # In case we use EngineRepository.register to inject the api_key and model => dynamically change the engine at runtime - if api_key is not None and model is not None: - self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] = api_key - self.config['NEUROSYMBOLIC_ENGINE_MODEL'] = model - if self.id() != 'neurosymbolic': - return # do not initialize if not neurosymbolic; avoids conflict with llama.cpp check in EngineRepository.register_from_package - openai.api_key = self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] - self.model = self.config['NEUROSYMBOLIC_ENGINE_MODEL'] - self.name = self.__class__.__name__ - try: - self.tokenizer = tiktoken.encoding_for_model(self.model) - except Exception as e: - self.tokenizer = tiktoken.get_encoding('o200k_base') - self.max_context_tokens = self.api_max_context_tokens() - self.max_response_tokens = self.api_max_response_tokens() - self.seed = None - - try: - self.client = openai.Client(api_key=openai.api_key) - except Exception as e: - CustomUserWarning(f'Failed to initialize OpenAI client. Please check your OpenAI library version. Caused by: {e}', raise_with=ValueError) - - def id(self) -> str: - if self.config.get('NEUROSYMBOLIC_ENGINE_MODEL') and \ - (self.config.get('NEUROSYMBOLIC_ENGINE_MODEL').startswith('o1') or \ - self.config.get('NEUROSYMBOLIC_ENGINE_MODEL').startswith('o3') or \ - self.config.get('NEUROSYMBOLIC_ENGINE_MODEL').startswith('o4')): - return 'neurosymbolic' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'NEUROSYMBOLIC_ENGINE_API_KEY' in kwargs: - openai.api_key = kwargs['NEUROSYMBOLIC_ENGINE_API_KEY'] - if 'NEUROSYMBOLIC_ENGINE_MODEL' in kwargs: - self.model = kwargs['NEUROSYMBOLIC_ENGINE_MODEL'] - if 'seed' in kwargs: - self.seed = kwargs['seed'] - - def compute_required_tokens(self, messages): - """Return the number of tokens used by a list of messages.""" - - if self.model in { - 'o1', - 'o3', - 'o3-mini', - 'o4-mini', - }: - tokens_per_message = 3 - tokens_per_name = 1 - else: - CustomUserWarning( - f"'num_tokens_from_messages()' is not implemented for model {self.model}. " - "See https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken for information on how messages are converted to tokens.", - raise_with=NotImplementedError - ) - - num_tokens = 0 - for message in messages: - num_tokens += tokens_per_message - for key, value in message.items(): - if type(value) == str: - num_tokens += len(self.tokenizer.encode(value, disallowed_special=())) - else: - for v in value: - if v['type'] == 'text': - num_tokens += len(self.tokenizer.encode(v['text'], disallowed_special=())) - if key == "name": - num_tokens += tokens_per_name - num_tokens += 3 # every reply is primed with <|start|>assistant<|message|> - return num_tokens - 1 # don't know where that extra 1 comes from - - def compute_remaining_tokens(self, prompts: list) -> int: - val = self.compute_required_tokens(prompts) - return min(self.max_context_tokens - val, self.max_response_tokens) - - def _handle_image_content(self, content: str) -> list: - """Handle image content by processing vision patterns and returning image file data.""" - def _extract_pattern(text): - pattern = r'<>' - return re.findall(pattern, text) - - image_files = [] - # pre-process prompt if contains image url - if self.model == 'o1' and '< max_frames_spacing: - CustomUserWarning(f"Invalid max_used_frames value: {max_used_frames}. Expected value between 1 and {max_frames_spacing}", raise_with=ValueError) - buffer, ext = encode_media_frames(img_) - if len(buffer) > 1: - step = len(buffer) // max_frames_spacing # max frames spacing - frames = [] - indices = list(range(0, len(buffer), step))[:max_used_frames] - for i in indices: - frames.append(f"data:image/{ext};base64,{buffer[i]}") - image_files.extend(frames) - elif len(buffer) == 1: - image_files.append(f"data:image/{ext};base64,{buffer[0]}") - else: - print('No frames found or error in encoding frames') - return image_files - - def _remove_vision_pattern(self, text: str) -> str: - """Remove vision patterns from text.""" - pattern = r'<>' - return re.sub(pattern, '', text) - - def truncate(self, prompts: list[dict], truncation_percentage: float | None, truncation_type: str) -> list[dict]: - """Main truncation method""" - def _slice_tokens(tokens, new_len, truncation_type): - """Slice tokens based on truncation type""" - new_len = max(100, new_len) # Ensure minimum token length - return tokens[-new_len:] if truncation_type == 'head' else tokens[:new_len] # else 'tail' - - if len(prompts) != 2 and all(prompt['role'] in ['developer', 'user'] for prompt in prompts): - # Only support developer and user prompts - CustomUserWarning(f"Token truncation currently supports only two messages, from 'user' and 'developer' (got {len(prompts)}). Returning original prompts.") - return prompts - - if truncation_percentage is None: - # Calculate smart truncation percentage based on model's max messages and completion tokens - truncation_percentage = (self.max_context_tokens - 16_384) / self.max_context_tokens - - system_prompt = prompts[0] - user_prompt = prompts[1] - - # Get token counts - system_tokens = Symbol(system_prompt['content']).tokens - user_tokens = [] - - if isinstance(user_prompt['content'], str): - # Default input format - user_tokens.extend(Symbol(user_prompt['content']).tokens) - elif isinstance(user_prompt['content'], list): - for content_item in user_prompt['content']: - # Image input format - if isinstance(content_item, dict): - if content_item.get('type') == 'text': - user_tokens.extend(Symbol(content_item['text']).tokens) - else: - # Image content; return original since not supported - return prompts - else: - CustomUserWarning(f"Invalid content type: {type(content_item)}. Format input according to the documentation. See https://platform.openai.com/docs/api-reference/chat/create?lang=python", raise_with=ValueError) - else: - # Unknown input format - CustomUserWarning(f"Unknown content type: {type(user_prompt['content'])}. Format input according to the documentation. See https://platform.openai.com/docs/api-reference/chat/create?lang=python", raise_with=ValueError) - - system_token_count = len(system_tokens) - user_token_count = len(user_tokens) - artifacts = self.compute_required_tokens(prompts) - (system_token_count + user_token_count) - assert artifacts >= 0, f"Artifacts count is negative: {artifacts}! Report bug!" - total_tokens = system_token_count + user_token_count + artifacts - - # Calculate maximum allowed tokens - max_prompt_tokens = int(self.max_context_tokens * truncation_percentage) - - # If total is within limit, return original - if total_tokens <= max_prompt_tokens: - return prompts - - CustomUserWarning( - f"Executing {truncation_type} truncation to fit within {max_prompt_tokens} tokens. " - f"Combined prompts ({total_tokens} tokens) exceed maximum allowed tokens " - f"of {max_prompt_tokens} ({truncation_percentage*100:.1f}% of context). " - f"You can control this behavior by setting 'truncation_percentage' (current: {truncation_percentage:.2f}) " - f"and 'truncation_type' (current: '{truncation_type}') parameters. " - f"Set 'truncation_percentage=1.0' to deactivate truncation (will fail if exceeding context window). " - f"Choose 'truncation_type' as 'head' to keep the end of prompts or 'tail' to keep the beginning." - ) - - # Case 1: Only user prompt exceeds - if user_token_count > max_prompt_tokens/2 and system_token_count <= max_prompt_tokens/2: - new_user_len = max_prompt_tokens - system_token_count - new_user_tokens = _slice_tokens(user_tokens, new_user_len, truncation_type) - return [ - {'role': 'developer', 'content': self.tokenizer.decode(system_tokens)}, - {'role': 'user', 'content': [{'type': 'text', 'text': self.tokenizer.decode(new_user_tokens)}]} - ] - - # Case 2: Only developer prompt exceeds - if system_token_count > max_prompt_tokens/2 and user_token_count <= max_prompt_tokens/2: - new_system_len = max_prompt_tokens - user_token_count - new_system_tokens = _slice_tokens(system_tokens, new_system_len, truncation_type) - return [ - {'role': 'developer', 'content': self.tokenizer.decode(new_system_tokens)}, - {'role': 'user', 'content': [{'type': 'text', 'text': self.tokenizer.decode(user_tokens)}]} - ] - - # Case 3: Both exceed - reduce proportionally - system_ratio = system_token_count / total_tokens - user_ratio = user_token_count / total_tokens - - new_system_len = int(max_prompt_tokens * system_ratio) - new_user_len = int(max_prompt_tokens * user_ratio) - distribute_tokens = max_prompt_tokens - new_system_len - new_user_len - new_system_len += distribute_tokens // 2 - new_user_len += distribute_tokens // 2 - - new_system_tokens = _slice_tokens(system_tokens, new_system_len, truncation_type) - new_user_tokens = _slice_tokens(user_tokens, new_user_len, truncation_type) - - return [ - {'role': 'developer', 'content': self.tokenizer.decode(new_system_tokens)}, - {'role': 'user', 'content': [{'type': 'text', 'text': self.tokenizer.decode(new_user_tokens)}]} - ] - - def forward(self, argument): - kwargs = argument.kwargs - truncation_percentage = kwargs.get('truncation_percentage', argument.prop.truncation_percentage) - truncation_type = kwargs.get('truncation_type', argument.prop.truncation_type) - messages = self.truncate(argument.prop.prepared_input, truncation_percentage, truncation_type) - payload = self._prepare_request_payload(messages, argument) - except_remedy = kwargs.get('except_remedy') - - try: - res = self.client.chat.completions.create(**payload) - - except Exception as e: - if openai.api_key is None or openai.api_key == '': - msg = 'OpenAI API key is not set. Please set it in the config file or pass it as an argument to the command method.' - logging.error(msg) - if self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] is None or self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] == '': - CustomUserWarning(msg, raise_with=ValueError) - openai.api_key = self.config['NEUROSYMBOLIC_ENGINE_API_KEY'] - - callback = self.client.chat.completions.create - kwargs['model'] = kwargs['model'] if 'model' in kwargs else self.model - - if except_remedy is not None: - res = except_remedy(self, e, callback, argument) - else: - CustomUserWarning(f'An error occurred while processing the request: {e}. ', raise_with=ValueError) - - metadata = {'raw_output': res} - if payload.get('tools'): - metadata = self._process_function_calls(res, metadata) - output = [r.message.content for r in res.choices] - - return output, metadata - - def _prepare_raw_input(self, argument): - if not argument.prop.processed_input: - CustomUserWarning('Need to provide a prompt instruction to the engine if raw_input is enabled.', raise_with=ValueError) - value = argument.prop.processed_input - # convert to dict if not already - if type(value) != list: - if type(value) != dict: - value = {'role': 'user', 'content': str(value)} - value = [value] - return value - - def prepare(self, argument): - if argument.prop.raw_input: - argument.prop.prepared_input = self._prepare_raw_input(argument) - return - - _non_verbose_output = """\nYou do not output anything else, like verbose preambles or post explanation, such as "Sure, let me...", "Hope that was helpful...", "Yes, I can help you with that...", etc. Consider well formatted output, e.g. for sentences use punctuation, spaces etc. or for code use indentation, etc. Never add meta instructions information to your output!\n\n""" - user: str = "" - developer: str = "" - - if argument.prop.suppress_verbose_output: - developer += _non_verbose_output - developer = f'{developer}\n' if developer and len(developer) > 0 else '' - - if argument.prop.response_format: - _rsp_fmt = argument.prop.response_format - assert _rsp_fmt.get('type') is not None, 'Expected format `{ "type": "json_object" }`! See https://platform.openai.com/docs/api-reference/chat/create#chat-create-response_format' - if _rsp_fmt["type"] == "json_object": - # OpenAI docs: - # "Important: when using JSON mode, you must also instruct the model - # to produce JSON yourself via a developer or user message" - developer += f'\nYou are a helpful assistant designed to output JSON.\n\n' - - ref = argument.prop.instance - static_ctxt, dyn_ctxt = ref.global_context - if len(static_ctxt) > 0: - developer += f"\n{static_ctxt}\n\n" - - if len(dyn_ctxt) > 0: - developer += f"\n{dyn_ctxt}\n\n" - - payload = argument.prop.payload - if argument.prop.payload: - developer += f"\n{str(payload)}\n\n" - - examples: List[str] = argument.prop.examples - if examples and len(examples) > 0: - developer += f"\n{str(examples)}\n\n" - - image_files = self._handle_image_content(str(argument.prop.processed_input)) - - if argument.prop.prompt is not None and len(argument.prop.prompt) > 0: - val = str(argument.prop.prompt) - if len(image_files) > 0: - val = self._remove_vision_pattern(val) - developer += f"\n{val}\n\n" - - suffix: str = str(argument.prop.processed_input) - if len(image_files) > 0: - suffix = self._remove_vision_pattern(suffix) - - user += f"{suffix}" - - if argument.prop.template_suffix: - developer += f' You will only generate content for the placeholder `{str(argument.prop.template_suffix)}` following the instructions and the provided context information.\n\n' - - if self.model == 'o1': - images = [{ 'type': 'image_url', "image_url": { "url": file }} for file in image_files] - user_prompt = { "role": "user", "content": [ - *images, - { 'type': 'text', 'text': user } - ]} - else: - user_prompt = { "role": "user", "content": user } - - # First check if the `Symbol` instance has the flag set, otherwise check if it was passed as an argument to a method - if argument.prop.instance._kwargs.get('self_prompt', False) or argument.prop.self_prompt: - self_prompter = SelfPrompt() - res = self_prompter({'user': user, 'developer': developer}) - if res is None: - CustomUserWarning("Self-prompting failed!", raise_with=ValueError) - - if len(image_files) > 0: - user_prompt = { "role": "user", "content": [ - *images, - { 'type': 'text', 'text': res['user'] } - ]} - else: - user_prompt = { "role": "user", "content": res['user'] } - - developer = res['developer'] - - argument.prop.prepared_input = [ - { "role": "developer", "content": developer }, - user_prompt, - ] - - def _process_function_calls(self, res, metadata): - hit = False - if hasattr(res, 'choices') and res.choices: - choice = res.choices[0] - if hasattr(choice, 'message') and choice.message: - if hasattr(choice.message, 'tool_calls') and choice.message.tool_calls: - for tool_call in choice.message.tool_calls: - if hit: - CustomUserWarning("Multiple function calls detected in the response but only the first one will be processed.") - break - if hasattr(tool_call, 'function') and tool_call.function: - try: - args_dict = json.loads(tool_call.function.arguments) - except json.JSONDecodeError: - args_dict = {} - metadata['function_call'] = { - 'name': tool_call.function.name, - 'arguments': args_dict - } - hit = True - return metadata - - def _prepare_request_payload(self, messages, argument): - """Prepares the request payload from the argument.""" - kwargs = argument.kwargs - - max_tokens = kwargs.get('max_tokens', None) - max_completion_tokens = kwargs.get('max_completion_tokens', None) - remaining_tokens = self.compute_remaining_tokens(messages) - - if max_tokens is not None: - CustomUserWarning( - "'max_tokens' is now deprecated in favor of 'max_completion_tokens', and is not compatible with o1 series models. " - "We handle this conversion by default for you for now but we won't in the future. " - "See: https://platform.openai.com/docs/api-reference/chat/create" - ) - if max_tokens > self.max_response_tokens: - CustomUserWarning( - f"Provided 'max_tokens' ({max_tokens}) exceeds max response tokens ({self.max_response_tokens}). " - f"Truncating to {remaining_tokens} to avoid API failure." - ) - kwargs['max_completion_tokens'] = remaining_tokens - else: - kwargs['max_completion_tokens'] = max_tokens - del kwargs['max_tokens'] - - if max_completion_tokens is not None: - if max_completion_tokens > self.max_response_tokens: - CustomUserWarning( - f"Provided 'max_completion_tokens' ({max_completion_tokens}) exceeds max response tokens ({self.max_response_tokens}). " - f"Truncating to {remaining_tokens} to avoid API failure." - ) - kwargs['max_completion_tokens'] = remaining_tokens - - payload = { - "messages": messages, - "model": kwargs.get('model', self.model), - "seed": kwargs.get('seed', self.seed), - "reasoning_effort": kwargs.get('reasoning_effort', 'medium'), - "max_completion_tokens": kwargs.get('max_completion_tokens'), - "stop": kwargs.get('stop', ''), - "temperature": kwargs.get('temperature', 1), - "frequency_penalty": kwargs.get('frequency_penalty', 0), - "presence_penalty": kwargs.get('presence_penalty', 0), - "top_p": kwargs.get('top_p', 1), - "n": kwargs.get('n', 1), - "logit_bias": kwargs.get('logit_bias'), - "tools": kwargs.get('tools'), - "tool_choice": kwargs.get('tool_choice'), - "response_format": kwargs.get('response_format'), - } - - if self.model == "o4-mini" or self.model == "o3": - del payload["stop"] - - return payload diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/ocr/engine_apilayer.py b/symbolicai-main/symbolicai-main/symai/backend/engines/ocr/engine_apilayer.py deleted file mode 100644 index ca9995045bb2543d531281f9ad35d567e424cc4f..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/ocr/engine_apilayer.py +++ /dev/null @@ -1,69 +0,0 @@ -import requests -from pathlib import Path - -from typing import Optional - -from ...base import Engine -from ...settings import SYMAI_CONFIG -from ....symbol import Result - - -class ApiLayerResult(Result): - def __init__(self, text, status_code=200, **kwargs): - super().__init__(**kwargs) - self.raw = text - try: - dict_ = self._to_symbol(text).ast() - self._value = dict_['all_text'] if 'all_text' in dict_ else f'OCR Engine Error: {text} - status code {status_code}' - except: - self._value = f'OCR Engine Error: {text} - status code {status_code}' - - -class OCREngine(Engine): - def __init__(self, api_key: Optional[str] = None): - super().__init__() - # Opening JSON file - self.config = SYMAI_CONFIG - self.headers = { - "apikey": self.config['OCR_ENGINE_API_KEY'] if api_key is None else api_key - } - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config['OCR_ENGINE_API_KEY']: - return 'ocr' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'OCR_ENGINE_API_KEY' in kwargs: - self.headers = { - "apikey": kwargs['OCR_ENGINE_API_KEY'] - } - - def forward(self, argument): - kwargs = argument.kwargs - image_url = argument.prop.image - - if image_url.startswith("file://"): - file_path = Path(image_url[7:]).resolve() - with open(file_path, "rb") as file: - payload = file.read() - url = "https://api.apilayer.com/image_to_text/upload" - response = requests.request("POST", url, headers=self.headers, data=payload) - else: - payload = {} - url = f"https://api.apilayer.com/image_to_text/url?url={image_url}" - response = requests.request("GET", url, headers=self.headers, data = payload) - - status_code = response.status_code - rsp = response.text - rsp = ApiLayerResult(response.text, status_code) - metadata = {} - - return [rsp], metadata - - def prepare(self, argument): - assert not argument.prop.processed_input, "OCREngine does not support processed_input." - image = str(argument.prop.image) - argument.prop.prepared_input = image diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/output/engine_stdout.py b/symbolicai-main/symbolicai-main/symai/backend/engines/output/engine_stdout.py deleted file mode 100644 index b7c594dd70f434778c238a6cd371a57562c13483..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/output/engine_stdout.py +++ /dev/null @@ -1,34 +0,0 @@ -from ...base import Engine - - -class OutputEngine(Engine): - def __init__(self): - super().__init__() - self.name = self.__class__.__name__ - - def id(self) -> str: - return 'output' - - def forward(self, argument): - expr, processed, args, kwargs = argument.prop.prepared_input - res = None - args = [] if args is None else args - kwargs = {} if kwargs is None else kwargs - if expr: - if processed: - res = expr(processed, *args, **kwargs) - else: - res = expr(*args, **kwargs) - - metadata = {} - result = { - 'result': res, - 'processed': processed, - 'args': args, - 'kwargs': kwargs - } - - return [result], metadata - - def prepare(self, argument): - argument.prop.prepared_input = argument.prop.expr, argument.prop.processed_input, argument.prop.args, argument.prop.kwargs diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/search/engine_openai.py b/symbolicai-main/symbolicai-main/symai/backend/engines/search/engine_openai.py deleted file mode 100644 index faa78c0a9fd2b168f5c2d7827b07c2ab53edad0e..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/search/engine_openai.py +++ /dev/null @@ -1,151 +0,0 @@ -import json -import logging -import requests -from copy import deepcopy -from dataclasses import dataclass - -from ....symbol import Result -from ....utils import CustomUserWarning -from ...base import Engine -from ...settings import SYMAI_CONFIG -from ...mixin import OPENAI_CHAT_MODELS, OPENAI_REASONING_MODELS - -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib3").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - - -@dataclass -class Citation: - id: str - title: str - url: str - start: int - end: int - - def __hash__(self): - return hash((self.url, )) - - -class SearchResult(Result): - def __init__(self, value, **kwargs) -> None: - super().__init__(value, **kwargs) - if value.get('error'): - CustomUserWarning(value['error'], raise_with=ValueError) - try: - for output in value.get('output', []): - if output.get('type') == 'message' and output.get('content'): - annotations = output['content'][0].get('annotations', []) - citations = [] - for n, annotation in enumerate(annotations): - if annotation.get('type') == 'url_citation': - citation = Citation( - id=f'[{n + 1}]', - start=annotation.get('start_index'), - end=annotation.get('end_index'), - title=annotation.get('title', ''), - url=annotation.get('url', ''), - ) - if citation not in citations: - citations.append(citation) - self._value = output['content'][0]['text'] - delta = 0 - for citation in citations: - self._value = self._value[:citation.start - delta] + citation.id + self._value[citation.end - delta:] - delta += (citation.end - citation.start) - len(citation.id) - self._citations = citations - - except Exception as e: - self._value = None - CustomUserWarning(f"Failed to parse response: {e}", raise_with=ValueError) - - def __str__(self) -> str: - try: - return json.dumps(self.raw, indent=2) - except TypeError: - return str(self.raw) - - def _repr_html_(self) -> str: - try: - return f"
    {json.dumps(self.raw, indent=2)}
    " - except Exception as e: - return f"
    {str(self.raw)}
    " - - def get_citations(self) -> list[Citation]: - return self._citations - - -class GPTXSearchEngine(Engine): - def __init__(self, api_key: str | None = None, model: str | None = None): - super().__init__() - self.config = deepcopy(SYMAI_CONFIG) - if api_key is not None and model is not None: - self.config['SEARCH_ENGINE_API_KEY'] = api_key - self.config['SEARCH_ENGINE_MODEL'] = model - self.api_key = self.config.get('SEARCH_ENGINE_API_KEY') - self.model = self.config.get('SEARCH_ENGINE_MODEL', 'gpt-4.1') # Default to gpt-4.1 as per docs - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config.get('SEARCH_ENGINE_API_KEY') and \ - self.config.get('SEARCH_ENGINE_MODEL') in OPENAI_CHAT_MODELS + OPENAI_REASONING_MODELS: - return 'search' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'SEARCH_ENGINE_API_KEY' in kwargs: - self.api_key = kwargs['SEARCH_ENGINE_API_KEY'] - if 'SEARCH_ENGINE_MODEL' in kwargs: - self.model = kwargs['SEARCH_ENGINE_MODEL'] - - def forward(self, argument): - messages = argument.prop.prepared_input - kwargs = argument.kwargs - - tool_definition = {"type": "web_search_preview"} - user_location = kwargs.get('user_location') - if user_location: - tool_definition['user_location'] = user_location - search_context_size = kwargs.get('search_context_size') - if search_context_size: - tool_definition['search_context_size'] = search_context_size - - self.model = kwargs.get('model', self.model) # Important for MetadataTracker to work correctly - payload = { - "model": self.model, - "input": messages, - "tools": [tool_definition], - "tool_choice": {"type": "web_search_preview"} # force the use of web search tool - } - - headers = { - "Authorization": f"Bearer {self.api_key}", - "Content-Type": "application/json", - "OpenAI-Beta": "assistants=v1" # Required for some beta features, might be useful - } - api_url = "https://api.openai.com/v1/responses" - - res = requests.post(api_url, json=payload, headers=headers) - res = SearchResult(res.json()) - - metadata = {"raw_output": res.raw} - output = [res] - - return output, metadata - - def prepare(self, argument): - system_message = "You are a helpful AI assistant. Be precise and informative." if argument.kwargs.get('system_message') is None else argument.kwargs.get('system_message') - - res = [ - { - "role": "system", - "content": system_message - }, - { - "role": "user", - "content": f"{argument.prop.query}" - } - ] - argument.prop.prepared_input = res diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/search/engine_perplexity.py b/symbolicai-main/symbolicai-main/symai/backend/engines/search/engine_perplexity.py deleted file mode 100644 index 81f6b1823fd987fda8e7ccc7643d4cdb2b672556..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/search/engine_perplexity.py +++ /dev/null @@ -1,110 +0,0 @@ -import json -import logging - -import requests - -from ....symbol import Result -from ....utils import CustomUserWarning -from ...base import Engine -from ...settings import SYMAI_CONFIG - -logging.getLogger("requests").setLevel(logging.ERROR) -logging.getLogger("urllib").setLevel(logging.ERROR) -logging.getLogger("httpx").setLevel(logging.ERROR) -logging.getLogger("httpcore").setLevel(logging.ERROR) - - -class SearchResult(Result): - def __init__(self, value, **kwargs) -> None: - super().__init__(value, **kwargs) - if value.get('error'): - CustomUserWarning(value['error'], raise_with=ValueError) - try: - self._value = value['choices'][0]['message']['content'] - except Exception as e: - self._value = None - CustomUserWarning(f"Failed to parse response: {e}", raise_with=ValueError) - - def __str__(self) -> str: - try: - return json.dumps(self.raw, indent=2) - except TypeError: - return str(self.raw) - - def _repr_html_(self) -> str: - try: - return f"
    {json.dumps(self.raw, indent=2)}
    " - except TypeError: - return f"
    {str(self.raw)}
    " - - -class PerplexityEngine(Engine): - def __init__(self): - super().__init__() - self.config = SYMAI_CONFIG - self.api_key = self.config['SEARCH_ENGINE_API_KEY'] - self.model = self.config['SEARCH_ENGINE_MODEL'] - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config.get('SEARCH_ENGINE_API_KEY') and self.config.get('SEARCH_ENGINE_MODEL').startswith("sonar"): - return 'search' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'SEARCH_ENGINE_API_KEY' in kwargs: - self.api_key = kwargs['SEARCH_ENGINE_API_KEY'] - if 'SEARCH_ENGINE_MODEL' in kwargs: - self.model = kwargs['SEARCH_ENGINE_MODEL'] - - def forward(self, argument): - messages = argument.prop.prepared_input - kwargs = argument.kwargs - - payload = { - "model": self.model, - "messages": messages, - "max_tokens": kwargs.get('max_tokens', None), - "temperature": kwargs.get('temperature', 0.2), - "top_p": kwargs.get('top_p', 0.9), - "search_domain_filter": kwargs.get('search_domain_filter', []), - "return_images": kwargs.get('return_images', False), - "return_related_questions": kwargs.get('return_related_questions', False), - "search_recency_filter": kwargs.get('search_recency_filter', "month"), - "top_k": kwargs.get('top_k', 0), - "stream": kwargs.get('stream', False), - "presence_penalty": kwargs.get('presence_penalty', 0), - "frequency_penalty": kwargs.get('frequency_penalty', 1), - "response_format": kwargs.get('response_format', None) - } - web_search_options = kwargs.get('web_search_options', None) - if web_search_options is not None: - payload["web_search_options"] = web_search_options - - headers = { - "Authorization": f"Bearer {self.api_key}", - "Content-Type": "application/json" - } - res = requests.post("https://api.perplexity.ai/chat/completions", json=payload, headers=headers) - res = SearchResult(res.json()) - - metadata = {"raw_output": res.raw} - output = [res] - - return output, metadata - - def prepare(self, argument): - system_message = "You are a helpful AI assistant. Be precise and informative." if argument.kwargs.get('system_message') is None else argument.kwargs.get('system_message') - - res = [ - { - "role": "system", - "content": system_message - }, - { - "role": "user", - "content": f"{argument.prop.query}" - } - ] - argument.prop.prepared_input = res diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/search/engine_serpapi.py b/symbolicai-main/symbolicai-main/symai/backend/engines/search/engine_serpapi.py deleted file mode 100644 index 6bb40eaa09fea58ee6c92f5627f608e73e153440..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/search/engine_serpapi.py +++ /dev/null @@ -1,106 +0,0 @@ -import json - -from IPython.utils import io - -from ....symbol import Result -from ....utils import CustomUserWarning -from ...base import Engine -from ...settings import SYMAI_CONFIG - -try: - from serpapi import GoogleSearch -except: - GoogleSearch = None - - -class SearchResult(Result): - def __init__(self, value, **kwargs) -> None: - super().__init__(value, **kwargs) - if 'answer_box' in value.keys() and 'answer' in value['answer_box'].keys(): - self._value = value['answer_box']['answer'] - elif 'answer_box' in value.keys() and 'snippet' in value['answer_box'].keys(): - self._value = value['answer_box']['snippet'] - elif 'answer_box' in value.keys() and 'snippet_highlighted_words' in value['answer_box'].keys(): - self._value = value['answer_box']["snippet_highlighted_words"][0] - elif 'organic_results' in value and 'snippet' in value["organic_results"][0].keys(): - self._value = value["organic_results"][0]['snippet'] - else: - self._value = value - - if 'organic_results' in value.keys(): - self.results = value['organic_results'] - if len(self.results) > 0: - self.links = [r['link'] for r in self.results] - else: - self.links = [] - else: - self.results = [] - self.links = [] - - def __str__(self) -> str: - json_str = json.dumps(self.raw, indent=2) - return json_str - - def _repr_html_(self) -> str: - json_str = json.dumps(self.raw, indent=2) - return json_str - - -class SerpApiEngine(Engine): - def __init__(self): - super().__init__() - self.config = SYMAI_CONFIG - self.api_key = self.config['SEARCH_ENGINE_API_KEY'] - self.engine = self.config['SEARCH_ENGINE_MODEL'] - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config.get('SEARCH_ENGINE_API_KEY') and self.config.get('SEARCH_ENGINE_MODEL') == "google": # only support Google for now - if GoogleSearch is None: - CustomUserWarning('SerpApi is not installed. Please install it with `pip install symbolicai[serpapi]`') - return 'search' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'SEARCH_ENGINE_API_KEY' in kwargs: - self.api_key = kwargs['SEARCH_ENGINE_API_KEY'] - if 'SEARCH_ENGINE_MODEL' in kwargs: - self.engine = kwargs['SEARCH_ENGINE_MODEL'] - - def forward(self, argument): - queries = argument.prop.prepared_input - kwargs = argument.kwargs - queries_ = queries if isinstance(queries, list) else [queries] - rsp = [] - engine = kwargs['engine'] if 'engine' in kwargs else self.engine - - for q in queries_: - query = { - "api_key": self.api_key, - "engine": engine, - "q": q, - "google_domain": "google.com", - "gl": "us", - "hl": "en" - } - - # send to Google - with io.capture_output() as captured: # disables prints from GoogleSearch - search = GoogleSearch(query) - res = search.get_dict() - - toret = SearchResult(res) - rsp.append(toret) - - metadata = {} - - output = rsp if isinstance(queries, list) else rsp[0] - output = [output] - return output, metadata - - def prepare(self, argument): - res = '' - res += str(argument.prop.query) - res += str(argument.prop.processed_input) - argument.prop.prepared_input = res diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/speech_to_text/engine_local_whisper.py b/symbolicai-main/symbolicai-main/symai/backend/engines/speech_to_text/engine_local_whisper.py deleted file mode 100644 index 774fa6c534405cc909f9a2048d133e34986ad02d..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/speech_to_text/engine_local_whisper.py +++ /dev/null @@ -1,191 +0,0 @@ -import logging -import torch - -from itertools import takewhile -from typing import Iterable, List, Optional - -from ...base import Engine -from ...settings import SYMAI_CONFIG -from ....symbol import Expression, Result - - -class WhisperTimestampsFormatter(Expression): - def __init__(self, **kwargs): - super().__init__(**kwargs) - - def forward(self, response: List[str]) -> str: - result = [] - for i, interval in enumerate(response): - interval = self._filter_empty_string(interval) - prev_end = 0.0 - prev_start = 0.0 - for head, tail in zip(interval[::2], interval[1::2]): - start = self._get_timestamp(head) - end = self._get_timestamp(tail) - if start >= prev_end: - start = prev_end - prev_end = end - prev_start = start - result.append(f"{self._format_to_hours(start + (i*30))} {self._get_sentence(head)}") - continue - if start < prev_start: - continue - delta = end - start - if start + prev_end > 30: - start = prev_end - else: - start += prev_end - if start + delta > 30: - end = 30 - else: - end = start + delta - prev_end = end - result.append(f"{self._format_to_hours(start + (i*30))} {self._get_sentence(head)}") - return "\n".join(result) - - def _filter_empty_string(self, s: str) -> List[str]: - return list(filter(lambda x: x, s.split("<|"))) - - def _get_timestamp(self, s: str) -> float: - return float("".join(list(takewhile(lambda x: x != "|", s)))) - - def _get_sentence(self, s: str) -> str: - return s.split("|>")[-1] - - def _format_to_hours(self, seconds: float) -> str: - hours = int(seconds // 3600) - seconds %= 3600 - minutes = int(seconds // 60) - seconds %= 60 - formatted_time = "{:02d}:{:02d}:{:02d}".format(hours, minutes, int(seconds)) - return formatted_time - - -class WhisperResult(Result): - def __init__(self, value, **kwargs) -> None: - super().__init__(value, **kwargs) - self.raw = None - - -try: - import whisper - from whisper.audio import \ - N_SAMPLES # @NOTE: sample_rate (16_000) * chunk_length (30) = 480_000 - from whisper.tokenizer import get_tokenizer -except ImportError: - whisper = None - N_SAMPLES = 16_000 * 30 - - -class WhisperEngine(Engine): - def __init__(self, model: Optional[str] = None): - super().__init__() - self.config = SYMAI_CONFIG - self.model = None # lazy loading - self.model_id = self.config['SPEECH_TO_TEXT_ENGINE_MODEL'] if model is None else model - self.old_model_id = self.config['SPEECH_TO_TEXT_ENGINE_MODEL'] if model is None else model - self.tokens = [] - self.text = [] - self.formatter = WhisperTimestampsFormatter() - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config['SPEECH_TO_TEXT_ENGINE_MODEL']: - if whisper is None: - print("Whisper is not installed. Please install it with `pip install symbolicai[whisper]`") - return 'speech-to-text' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'SPEECH_TO_TEXT_ENGINE_MODEL' in kwargs: - self.model_id = kwargs['SPEECH_TO_TEXT_ENGINE_MODEL'] - - def forward(self, argument): - assert whisper is not None, "Whisper is not installed. Please install it first." - kwargs = argument.kwargs - (_, audio) = argument.prop.prepared_input - prompt = argument.prop.prompt - - if self.model is None or self.model_id != self.old_model_id: - device_fallback = 'cpu' - device = "cuda" if torch.cuda.is_available() else device_fallback - device = kwargs['device'] if 'device' in kwargs else device # user preference over auto detection - try: - self.model = whisper.load_model(self.model_id, device=device) - except RuntimeError: - logging.warn(f"Whisper failed to load model on device {device}. Fallback to {device_fallback}.") - self.model = whisper.load_model(self.model_id, device=device_fallback) - self.old_model_id = self.model_id - - self._try_compile() - show_pbar = kwargs.get("progress", False) - language = kwargs.get("language", "en") - temperature = kwargs.get("temperature", (0.0, 0.2, 0.4, 0.6, 0.8, 1.0)) - without_timestamps = kwargs.get("without_timestamps", False) - - raw_result = [] - if prompt == 'detect_language': - #@NOTE: the accuracy of mel spectrogram is not good enough; don't use it to transcribe - audio = whisper.pad_or_trim(audio) - mel = whisper.log_mel_spectrogram(audio).to(self.model.device) - _, probs = self.model.detect_language(mel) - rsp = max(probs, key=probs.get) - elif prompt == 'decode': - if show_pbar: - # supress tqdm warning - from tqdm import tqdm - pbar = tqdm(self._get_chunks(audio)) - else: - pbar = self._get_chunks(audio) - for chunk in pbar: - result = self.model.transcribe( - chunk, - language=language, - without_timestamps=without_timestamps, - temperature=temperature, - fp16=False, - ) - raw_result.append(result) - self.text.append(result["text"]) - self.tokens.append([ - token - for segment in result["segments"] - for token in segment["tokens"] - ]) - if without_timestamps is not None: - tokenizer = get_tokenizer(self.model.is_multilingual) - tokens = [tokenizer.decode_with_timestamps(t) for t in self.tokens] - rsp = self.formatter(tokens) - else: - rsp = " ".join(self.text) - else: - raise Exception(f"Unknown whisper command prompt: {prompt}") - - metadata = {} - - rsp = WhisperResult(rsp) - if raw_result: - rsp.raw = raw_result - return [rsp], metadata - - def prepare(self, argument): - assert not argument.prop.processed_input, "Whisper does not support processed_input." - assert argument.prop.audio, "Whisper requires audio input." - audio_file = str(argument.prop.audio) - audio = whisper.load_audio(audio_file) - argument.prop.prepared_input = (audio_file, audio) - - def _get_chunks(self, it: Iterable, batch: int = N_SAMPLES) -> torch.Tensor: - """ - Split an iterable into chunks of size `batch`. It defaults to `N_SAMPLES` 480_000 samples which is equal to 30 seconds. - """ - size = len(it) - for i in range(0, size, batch): - yield torch.tensor(it[i:min(i + batch, size)]).to(self.model.device) - - def _try_compile(self): - try: - self.model = torch.compile(self.model) - except Exception: - pass diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/symbolic/engine_wolframalpha.py b/symbolicai-main/symbolicai-main/symai/backend/engines/symbolic/engine_wolframalpha.py deleted file mode 100644 index f1115f23667fa29e3ca4e6d0938e0b58f655c5b2..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/symbolic/engine_wolframalpha.py +++ /dev/null @@ -1,66 +0,0 @@ -import json - -from box import Box - -from typing import Optional - -from ...base import Engine -from ...settings import SYMAI_CONFIG -from ....symbol import Result - -try: - import wolframalpha as wa -except: - wa = None - - -class WolframResult(Result): - def __init__(self, value) -> None: - super().__init__(value) - self.raw = Box(value) - self._value = value - - -class WolframAlphaEngine(Engine): - def __init__(self, api_key: Optional[str] = None): - super().__init__() - self.config = SYMAI_CONFIG - self.api_key = self.config['SYMBOLIC_ENGINE_API_KEY'] if api_key is None else api_key - self.client = None - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config['SYMBOLIC_ENGINE_API_KEY']: - if wa is None: - print('WolframAlpha is not installed. Please install it with `pip install symbolicai[wolframalpha]`') - return 'symbolic' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'SYMBOLIC_ENGINE_API_KEY' in kwargs: - self.api_key = kwargs['SYMBOLIC_ENGINE_API_KEY'] - self.client = wa.Client(self.api_key) if len(self.api_key) > 0 else None - - def forward(self, argument): - queries = argument.prop.prepared_input - - if self.client is None: - self.client = wa.Client(self.api_key) if len(self.api_key) > 0 else None - - queries_ = queries if isinstance(queries, list) else [queries] - rsp = [] - - rsp = self.client.query(queries) - rsp = WolframResult(rsp) - - metadata = {} - if 'metadata' in argument.kwargs and argument.kwargs['metadata']: - metadata['kwargs'] = argument.kwargs - metadata['input'] = queries_ - metadata['output'] = rsp - - return [rsp], metadata - - def prepare(self, argument): - argument.prop.prepared_input = str(argument.prop.processed_input) diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/text_to_speech/engine_openai.py b/symbolicai-main/symbolicai-main/symai/backend/engines/text_to_speech/engine_openai.py deleted file mode 100644 index 44ef60010fb82a474db23e0683491e5f89f396ae..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/text_to_speech/engine_openai.py +++ /dev/null @@ -1,61 +0,0 @@ -import logging - -from openai import OpenAI -from typing import Optional - -# suppress openai logging -logging.getLogger("openai").setLevel(logging.WARNING) - -from ...base import Engine -from ...settings import SYMAI_CONFIG -from ....symbol import Result - - -class TTSEngine(Engine): - def __init__(self, api_key: Optional[str] = None, model: Optional[str] = None): - super().__init__() - self.config = SYMAI_CONFIG - self.api_key = self.config['TEXT_TO_SPEECH_ENGINE_API_KEY'] if api_key is None else api_key - self.model_id = self.config['TEXT_TO_SPEECH_ENGINE_MODEL'] if model is None else model - self.tokens = [] - self.text = [] - self.client = OpenAI(api_key=self.api_key) - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config['TEXT_TO_SPEECH_ENGINE_API_KEY']: - return 'text-to-speech' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'TEXT_TO_SPEECH_ENGINE_API_KEY' in kwargs: - self.api_key = kwargs['TEXT_TO_SPEECH_ENGINE_API_KEY'] - if 'TEXT_TO_SPEECH_ENGINE_MODEL' in kwargs: - self.model_id = kwargs['TEXT_TO_SPEECH_ENGINE_MODEL'] - - def forward(self, argument): - kwargs = argument.kwargs - voice, path, prompt = argument.prop.prepared_input - - rsp = self.client.audio.speech.create( - model=self.model_id, - voice=voice, - input=prompt - ) - - metadata = {} - - rsp.stream_to_file(path) - - rsp = Result(rsp) - return [rsp], metadata - - def prepare(self, argument): - assert not argument.prop.processed_input, "TTSEngine does not support processed_input." - assert 'voice' in argument.kwargs, "TTS requires voice selection." - assert 'path' in argument.kwargs, "TTS requires path selection." - voice = str(argument.kwargs['voice']).lower() - audio_file = str(argument.kwargs['path']) - prompt = str(argument.prop.prompt) - argument.prop.prepared_input = (voice, audio_file, prompt) diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/text_vision/engine_clip.py b/symbolicai-main/symbolicai-main/symai/backend/engines/text_vision/engine_clip.py deleted file mode 100644 index 6d19994ac5870bc95f38dd477415684917af6c80..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/text_vision/engine_clip.py +++ /dev/null @@ -1,91 +0,0 @@ -import logging -import requests - -import torch -from typing import Optional -from PIL import Image -from io import BytesIO -from transformers import CLIPModel, CLIPProcessor - -from ...base import Engine -from ...settings import SYMAI_CONFIG - - -# supress warnings -logging.getLogger("PIL").setLevel(logging.WARNING) - - -class CLIPEngine(Engine): - def __init__(self, model: Optional[str] = None): - super().__init__() - self.model = None # lazy loading - self.preprocessor = None # lazy loading - self.config = SYMAI_CONFIG - self.model_id = self.config['VISION_ENGINE_MODEL'] if model is None else model - self.old_model_id = self.config['VISION_ENGINE_MODEL'] if model is None else model - self.name = self.__class__.__name__ - - def id(self) -> str: - if self.config['VISION_ENGINE_MODEL']: - return 'text_vision' - return super().id() # default to unregistered - - def command(self, *args, **kwargs): - super().command(*args, **kwargs) - if 'VISION_ENGINE_MODEL' in kwargs: - self.model_id = kwargs['VISION_ENGINE_MODEL'] - - def load_images(self, image): - images = [] - if not isinstance(image, (list, tuple)): - image = [image] - - for img in image: - if isinstance(img, bytes): - images.append(Image.open(BytesIO(img))) - elif isinstance(img, str): - if img.startswith('http'): - image_ = requests.get(img, stream=True).raw - else: - image_ = img - image = Image.open(image_) - images.append(image) - return images - - def forward(self, argument): - image_url, text = argument.prop.prepared_input - - if self.model is None or self.model_id != self.old_model_id: - self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - self.model = CLIPModel.from_pretrained(self.model_id).to(self.device) - self.processor = CLIPProcessor.from_pretrained(self.model_id) - self.old_model_id = self.model_id - - if text is None and image_url is not None: - image = self.load_images(image_url) - inputs = self.processor(images=image, return_tensors="pt").to(self.device) - rsp = self.model.get_image_features(**inputs) - elif image_url is None and text is not None: - inputs = self.processor(text=text, return_tensors="pt").to(self.device) - rsp = self.model.get_text_features(**inputs) - elif image_url is not None and text is not None: - image = self.load_images(image_url) - inputs = self.processor(text=text, images=image, return_tensors="pt", padding=True).to(self.device) - outputs = self.model(**inputs) - logits_per_image = outputs.logits_per_image # this is the image-text similarity score - rsp = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities - else: - raise NotImplementedError("CLIPEngine requires either image or text input.") - - rsp = rsp.squeeze().detach().cpu().numpy() - - metadata = {} - - return [rsp], metadata - - def prepare(self, argument): - assert not argument.prop.processed_input, "CLIPEngine does not support processed_input." - kwargs = argument.kwargs - image_url = argument.kwargs['image'] if 'image' in kwargs else None - text = argument.kwargs['text'] if 'text' in kwargs else None - argument.prop.prepared_input = (image_url, text) diff --git a/symbolicai-main/symbolicai-main/symai/backend/engines/userinput/engine_console.py b/symbolicai-main/symbolicai-main/symai/backend/engines/userinput/engine_console.py deleted file mode 100644 index 2237934fa81f7a7f0f4ce79b2c730a968c83cec0..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/engines/userinput/engine_console.py +++ /dev/null @@ -1,31 +0,0 @@ -from typing import List - -from ...base import Engine - - -class UserInputEngine(Engine): - def __init__(self): - super().__init__() - self.name = self.__class__.__name__ - - def id(self) -> str: - return 'userinput' - - def forward(self, argument): - msg = argument.prop.prepared_input - kwargs = argument.kwargs - - mock = kwargs['mock'] if 'mock' in kwargs else False - if mock: # mock user input - print(msg, end='') # print prompt - rsp = mock - else: - rsp = input(msg) - - metadata = {} - - return [rsp], metadata - - def prepare(self, argument): - # here the prompt marks the user input message - argument.prop.prepared_input = str(argument.prop.processed_input) diff --git a/symbolicai-main/symbolicai-main/symai/backend/mixin/__init__.py b/symbolicai-main/symbolicai-main/symai/backend/mixin/__init__.py deleted file mode 100644 index c87d32931783780aa5493c21a78965c585a3353c..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/mixin/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -from .anthropic import SUPPORTED_CHAT_MODELS as ANTHROPIC_CHAT_MODELS -from .anthropic import SUPPORTED_REASONING_MODELS as ANTHROPIC_REASONING_MODELS -from .deepseek import SUPPORTED_CHAT_MODELS as DEEPSEEK_CHAT_MODELS -from .deepseek import SUPPORTED_REASONING_MODELS as DEEPSEEK_REASONING_MODELS -from .google import SUPPORTED_CHAT_MODELS as GOOGLE_CHAT_MODELS -from .google import SUPPORTED_REASONING_MODELS as GOOGLE_REASONING_MODELS -from .openai import SUPPORTED_CHAT_MODELS as OPENAI_CHAT_MODELS -from .openai import SUPPORTED_REASONING_MODELS as OPENAI_REASONING_MODELS diff --git a/symbolicai-main/symbolicai-main/symai/backend/mixin/anthropic.py b/symbolicai-main/symbolicai-main/symai/backend/mixin/anthropic.py deleted file mode 100644 index 3b53f562470c96f98041d3724e8ff81ad2b2bce0..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/mixin/anthropic.py +++ /dev/null @@ -1,47 +0,0 @@ -# https://docs.anthropic.com/en/docs/about-claude/models -SUPPORTED_CHAT_MODELS = [ - 'claude-3-5-sonnet-latest', - 'claude-3-5-haiku-latest', - 'claude-3-5-sonnet-20241022', - 'claude-3-5-sonnet-20240620', - 'claude-3-opus-latest', - 'claude-3-opus-20240229', - 'claude-3-sonnet-20240229', - 'claude-3-haiku-20240307', -] -SUPPORTED_REASONING_MODELS = [ - "claude-opus-4-0", - "claude-sonnet-4-0", - 'claude-3-7-sonnet-latest', -] - -class AnthropicMixin: - def api_max_context_tokens(self): - if self.model == 'claude-opus-4-0' or \ - self.model == 'claude-sonnet-4-0' or \ - self.model == 'claude-3-7-sonnet-latest' or \ - self.model == 'claude-3-5-sonnet-latest' or \ - self.model == 'claude-3-5-sonnet-20241022' or \ - self.model == 'claude-3-5-sonnet-20240620' or \ - self.model == 'claude-3-opus-latest' or \ - self.model == 'claude-3-opus-20240229' or \ - self.model == 'claude-3-sonnet-20240229' or \ - self.model == 'claude-3-haiku-20240307': - return 200_000 - - def api_max_response_tokens(self): - if self.model == 'claude-sonnet-4-0' or \ - self.model == 'claude-3-7-sonnet-latest': - return 64_000 - if self.model == 'claude-opus-4-0': - return 32_000 - if self.model == 'claude-3-5-sonnet-latest' or \ - self.model == 'claude-3-5-sonnet-20241022' or \ - self.model == 'claude-3-5-haiku-latest': - return 8_192 - if self.model == 'claude-3-5-sonnet-20240620' or \ - self.model == 'claude-3-opus-latest' or \ - self.model == 'clade-3-opus-20240229' or \ - self.model == 'claude-3-sonnet-20240229' or \ - self.model == 'claude-3-haiku-20240307': - return 4_096 diff --git a/symbolicai-main/symbolicai-main/symai/backend/mixin/deepseek.py b/symbolicai-main/symbolicai-main/symai/backend/mixin/deepseek.py deleted file mode 100644 index c3e0c16b7a9a24436a5b9f5e24bf1d345a0f8206..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/mixin/deepseek.py +++ /dev/null @@ -1,14 +0,0 @@ -# https://api-docs.deepseek.com/quick_start/pricing -SUPPORTED_CHAT_MODELS = [] -SUPPORTED_REASONING_MODELS = [ - 'deepseek-reasoner' -] - -class DeepSeekMixin: - def api_max_context_tokens(self): - if self.model == 'deepseek-reasoner': - return 64_000 - - def api_max_response_tokens(self): - if self.model == 'deepseek-reasoner': - return 8_000 diff --git a/symbolicai-main/symbolicai-main/symai/backend/mixin/google.py b/symbolicai-main/symbolicai-main/symai/backend/mixin/google.py deleted file mode 100644 index 3487c26c15d6152a517ac001c466837a68be8f9d..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/mixin/google.py +++ /dev/null @@ -1,16 +0,0 @@ -# https://ai.google.dev/gemini-api/docs/models/gemini -SUPPORTED_CHAT_MODELS = [] -SUPPORTED_REASONING_MODELS = [ - # Check the latest snapshots; ie. *-06-05, etc - 'gemini-2.5-pro', - 'gemini-2.5-flash', -] - -class GoogleMixin: - def api_max_context_tokens(self): - if self.model.startswith('gemini-2.5-'): - return 1_048_576 - - def api_max_response_tokens(self): - if self.model == 'gemini-2.5-': - return 65_536 diff --git a/symbolicai-main/symbolicai-main/symai/backend/mixin/openai.py b/symbolicai-main/symbolicai-main/symai/backend/mixin/openai.py deleted file mode 100644 index f272d8b64a867772ecb24e0406bea04717e46ad9..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/mixin/openai.py +++ /dev/null @@ -1,120 +0,0 @@ -SUPPORTED_COMPLETION_MODELS = [ - 'davinci-002', -] -SUPPORTED_CHAT_MODELS = [ - 'gpt-3.5-turbo', - 'gpt-3.5-turbo-16k', - 'gpt-3.5-turbo-1106', - 'gpt-3.5-turbo-0613', - 'gpt-4', - 'gpt-4-0613', - 'gpt-4-1106-preview', # @NOTE: probabily obsolete; same price as 'gpt-4-turbo-2024-04-09' but no vision - 'gpt-4-turbo', - 'gpt-4-turbo-2024-04-09', - 'gpt-4o', - 'gpt-4o-2024-11-20', - 'gpt-4o-mini', - 'chatgpt-4o-latest', - 'gpt-4.1', - 'gpt-4.1-mini', - 'gpt-4.1-nano', -] -SUPPORTED_REASONING_MODELS = [ - 'o3-mini', - 'o4-mini', - 'o1', - 'o3' -] -SUPPORTED_EMBEDDING_MODELS = [ - 'text-embedding-ada-002', - 'text-embedding-3-small', - 'text-embedding-3-large' -] - - -class OpenAIMixin: - def api_max_context_tokens(self): - if self.model == 'text-curie-001' or \ - self.model == 'text-babbage-001' or \ - self.model == 'text-ada-001' or \ - self.model == 'davinci' or \ - self.model == 'curie' or \ - self.model == 'babbage' or \ - self.model == 'ada': - return 2_049 - if self.model == 'gpt-3.5-turbo' or \ - self.model == 'gpt-3.5-turbo-0613' or \ - self.model == 'gpt-3.5-turbo-1106': - return 4_096 - if self.model == 'gpt-4' or \ - self.model == 'gpt-4-0613' or \ - self.model == 'text-embedding-ada-002' or \ - self.model == 'text-embedding-3-small' or \ - self.model == 'text-embedding-3-large': - return 8_192 - if self.model == 'gpt-3.5-turbo-16k' or \ - self.model == 'gpt-3.5-turbo-16k-0613' or \ - self.model == 'davinci-002': - return 16_384 - if self.model == 'gpt-4-32k' or \ - self.model == 'gpt-4-32k-0613': - return 32_768 - if self.model == 'gpt-4-1106-preview' or \ - self.model == 'gpt-4-turbo-2024-04-09' or \ - self.model == 'gpt-4-turbo' or \ - self.model == 'gpt-4-1106' or \ - self.model == 'gpt-4o' or \ - self.model == 'gpt-4o-2024-11-20' or \ - self.model == 'gpt-4o-mini' or \ - self.model == 'chatgpt-4o-latest': - return 128_000 - if self.model == 'o1' or \ - self.model == 'o3' or \ - self.model == 'o3-mini' or \ - self.model == 'o4-mini': - return 200_000 - if self.model == 'gpt-4.1' or \ - self.model == 'gpt-4.1-mini' or \ - self.model == 'gpt-4.1-nano': - return 1_047_576 - raise ValueError(f'Unsupported model: {self.model}') - - def api_max_response_tokens(self): - if self.model == 'davinci-002': - return 2_048 - if self.model == 'gpt-4-turbo' or \ - self.model == 'gpt-4-turbo-2024-04-09' or \ - self.model == 'gpt-4-1106-preview' or \ - self.model == 'gpt-3.5-turbo-1106' or \ - self.model == 'gpt-3.5-turbo-0613' or \ - self.model == 'gpt-3.5-turbo': - return 4_096 - if self.model == 'gpt-4-0613' or \ - self.model == 'gpt-4': - return 8_192 - if self.model == 'gpt-3.5-turbo-16k-0613' or \ - self.model == 'gpt-3.5-turbo-16k' or \ - self.model == 'gpt-4o-mini' or \ - self.model == 'gpt-4o' or \ - self.model == 'gpt-4o-2024-11-20' or \ - self.model == 'chatgpt-4o-latest': - return 16_384 - if self.model == 'gpt-4.1' or \ - self.model == 'gpt-4.1-mini' or \ - self.model == 'gpt-4.1-nano': - return 32_768 - if self.model == 'o1' or \ - self.model == 'o3' or \ - self.model == 'o3-mini' or \ - self.model == 'o4-mini': - return 100_000 - raise ValueError(f'Unsupported model: {self.model}') - - def api_embedding_dims(self): - if self.model == 'text-embedding-ada-002': - return 1_536 - if self.model == 'text-embedding-3-small': - return 1_536 - if self.model == 'text-embedding-3-large': - return 3_072 - raise ValueError(f'Unsupported model: {self.model}') diff --git a/symbolicai-main/symbolicai-main/symai/backend/settings.py b/symbolicai-main/symbolicai-main/symai/backend/settings.py deleted file mode 100644 index bbf4027a4bcd5b0606fe7d790b656d3093e3bdfe..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/backend/settings.py +++ /dev/null @@ -1,79 +0,0 @@ -import json -import os -import sys -from pathlib import Path - - -class SymAIConfig: - """Manages SymbolicAI configuration files across different environments. - Configuration Priority: - 1. Debug mode (current working directory) - 2. Python environment-specific config - 3. User home directory config - """ - - def __init__(self): - """Initialize configuration paths based on current Python environment.""" - self._env_path = Path(sys.prefix) - self._env_config_dir = self._env_path / '.symai' - self._home_config_dir = Path.home() / '.symai' - self._debug_dir = Path.cwd() # Current working directory for debug mode - - @property - def config_dir(self) -> Path: - """Returns the active configuration directory based on priority system.""" - # Debug mode takes precedence - if (self._debug_dir / 'symai.config.json').exists(): - return self._debug_dir - # Then environment config - if self._env_config_dir.exists(): - return self._env_config_dir - # Finally home directory - return self._home_config_dir - - def get_config_path(self, filename: str, fallback_to_home: bool = False) -> Path: - """Gets the config path using the priority system or forces fallback to home.""" - debug_config = self._debug_dir / filename - env_config = self._env_config_dir / filename - home_config = self._home_config_dir / filename - - # Check debug first (only valid for symai.config.json) - if filename == 'symai.config.json' and debug_config.exists(): - return debug_config - - # If forced to fallback, return home config if it exists, otherwise environment - if fallback_to_home: - return home_config if home_config.exists() else env_config - - # Normal priority-based resolution - # If environment config doesn't exist, return that path (for creation) - if not env_config.exists(): - return env_config - # Otherwise use environment config - return env_config - - def load_config(self, filename: str, fallback_to_home: bool = False) -> dict: - """Loads JSON data from the determined config location.""" - config_path = self.get_config_path(filename, fallback_to_home=fallback_to_home) - if not config_path.exists(): - return {} - with open(config_path, 'r', encoding='utf-8') as f: - return json.load(f) - - def save_config(self, filename: str, data: dict, fallback_to_home: bool = False) -> None: - """Saves JSON data to the determined config location.""" - config_path = self.get_config_path(filename, fallback_to_home=fallback_to_home) - os.makedirs(config_path.parent, exist_ok=True) - with open(config_path, 'w', encoding='utf-8') as f: - json.dump(data, f, indent=4) - - def migrate_config(self, filename: str, updates: dict) -> None: - """Updates existing configuration with new fields.""" - config = self.load_config(filename) - config.update(updates) - self.save_config(filename, config) - -SYMAI_CONFIG = {} -SYMSH_CONFIG = {} -SYMSERVER_CONFIG = {} -HOME_PATH = Path(SymAIConfig().config_dir) diff --git a/symbolicai-main/symbolicai-main/symai/chat.py b/symbolicai-main/symbolicai-main/symai/chat.py deleted file mode 100644 index 52fc391870a6afb56699be65493fbd5f04cbf2c6..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/chat.py +++ /dev/null @@ -1,310 +0,0 @@ -import logging -import re - -from typing import Optional - -from .backend import settings as settings -from .components import (IncludeFilter, InContextClassification, - Outline, Output, Sequence) -from .memory import Memory, SlidingWindowListMemory, VectorDatabaseMemory -from .post_processors import ConsolePostProcessor, StripPostProcessor -from .pre_processors import ConsoleInputPreProcessor -from .prompts import MemoryCapabilities, SymbiaCapabilities -from .symbol import Expression, Symbol -from .interfaces import Interface -from . import core - -logging.getLogger('charset_normalizer').setLevel(logging.ERROR) - - -class ChatBot(Expression): - _symai_chat: str = '''This is a conversation between a chatbot (Symbia:) and a human (User:). The chatbot follows a narrative structure, primarily relying on the provided instructions. It uses the user's input as a conditioning factor to generate its responses. Whenever Symbia retrieves any long-term memories, it checks the user's query and incorporates information from the long-term memory buffer into its response. If the long-term memories cannot provide a suitable answer, Symbia then checks its short-term memory to be aware of the topics discussed in the recent conversation rounds. Your primary task is to reply to the user's question or statement by generating a relevant and contextually appropriate response. Do not focus on filling the scratchpad with narration, long-term memory recall, short-term memory recall, or reflections. Always consider any follow-up questions or relevant information from the user to generate a response that is contextually relevant. Endeavor to reply to the greatest possible effort.''' - - def __init__(self, value = None, name: str = 'Symbia', output: Optional[Output] = None, verbose: bool = False, **kwargs): - super().__init__(value, **kwargs) - self.sym_return_type = ChatBot - self.verbose: bool = verbose - self.name = name - self.last_user_input: str = '' - self.dalle = Interface('dall_e') - self.search = Interface('serpapi') - self.crawler = Interface('selenium') - self.speech = Interface('whisper') - self.ocr = Interface('ocr') - - self.short_term_memory: Memory = SlidingWindowListMemory(window_size=10) - self.long_term_memory: Memory = VectorDatabaseMemory(enabled=settings.SYMAI_CONFIG['INDEXING_ENGINE_API_KEY'] is not None, top_k=10) - - self._preprocessor = ChatBot._init_custom_input_preprocessor(name=name, that=self) - self._postprocessor = ChatBot._init_custom_input_postprocessor(that=self) - - self.detect_capability = InContextClassification(SymbiaCapabilities()) - self.detect_memory_usage = InContextClassification(MemoryCapabilities()) - - self.expression = Interface('wolframalpha') - - def repeat(self, query, **kwargs): - return self.narrate('Symbia does not understand and asks to repeat and give more context.', prompt=query) - - def narrate(self, message: str, context: str = None, category: str = None, end: bool = False, **kwargs) -> Symbol: - reflection = context if context is not None else '' - ltmem_recall = 'No memories retrieved.' - stmem_recall = '\n'.join(self.short_term_memory.recall()) - stmem_recall = stmem_recall if len(stmem_recall) > 0 else 'No memories retrieved.' - - if category == 'RECALL': - ltmem_recall = '\n'.join(self.long_term_memory.recall(reflection)) - ltmem_recall = ltmem_recall if len(ltmem_recall) > 0 else 'No memories retrieved.' - scratchpad = self._memory_scratchpad(reflection, stmem_recall, ltmem_recall) - memory_usage = str(self.detect_memory_usage(scratchpad)) - - if self.verbose: - logging.debug(f'Scratchpad:\n{scratchpad}\n') - logging.debug(f'Memory usage:\n{memory_usage}\n') - logging.debug(f'Retrieved from short-term memory:\n{stmem_recall}\n') - logging.debug(f'Retrieved from long-term memory:\n{ltmem_recall}\n') - - do = self._extract_category(memory_usage) - reflection = self._extract_reflection(memory_usage) - - if do == 'SAVE': - self.long_term_memory.store(f'{self.name}: {reflection}') - if self.verbose: logging.debug(f'Store new long-term memory:\n{reflection}\n') - message = f'{self.name} inform the user that the memory was stored.' - - elif do == 'DUPLICATE': - message = f'{self.name} engages the user in a conversation about the duplicate topic, showing the user she remembered the past interaction.' - - elif do == 'IRRELEVANT': - message = f'{self.name} discusses the topic with the user.' - - else: pass - - if self.verbose: - logging.debug(f'Storing new short-term memory:\nUser: {self.last_user_input}\n') - logging.debug(f'Storing new short-term memory:\n{self.name}: {reflection}\n') - - reply = f'{self.name}: {self._narration(message, self.last_user_input, reflection, ltmem_recall, stmem_recall, **kwargs)}' - - if end: print('\n\n', reply) - - return Symbol(reply) - - def input(self, message: str = "Please add more information", **kwargs) -> Symbol: - @core.userinput( - pre_processors=[self._preprocessor()], - post_processors=[StripPostProcessor(), - self._postprocessor()], - **kwargs - ) - def _func(_, message) -> str: - pass - - return Symbol(_func(self, message)) - - @property - def static_context(self) -> str: - return ChatBot._symai_chat.format(self.name) - - @staticmethod - def _init_custom_input_preprocessor(name, that): - class CustomInputPreProcessor(ConsoleInputPreProcessor): - def __call__(self, argument): - msg = re.sub(f'{name}:\s*', '', str(argument.args[0])) - console = f'\n{name}: {msg}\n$> ' - - if len(msg) > 0: - that.short_term_memory.store(f'{name}: ' + msg) - - return console - - return CustomInputPreProcessor - - @staticmethod - def _init_custom_input_postprocessor(that): - class CustomInputPostProcessor(ConsolePostProcessor): - def __call__(self, rsp, argument): - that.short_term_memory.store(f'User: {str(rsp)}') - - return rsp - - return CustomInputPostProcessor - - - def _narration(self, msg: str, query: str, reflection: str, ltmem_recall: str, stmem_recall: str, **kwargs): - prompt = f''' -{self._symai_chat.format(self.name)} - - [NARRATION]( -{msg} -) - - [LONG-TERM MEMORY RECALL]( -{ltmem_recall} -) - - [SHORT-TERM MEMORY RECALL]( -{stmem_recall} -) - - [USER]( -{query} -) - - [REFLECTION]( -{reflection} -) - -The chatbot always reply in the following format -{self.name}: -''' - @core.zero_shot(prompt=prompt, **kwargs) - def _func(_) -> str: - pass - if self.verbose: logging.debug(f'Narration:\n{prompt}\n') - res = _func(self) - res = res.replace(f'{self.name}: ', '').strip() - return res - -class SymbiaChat(ChatBot): - def __init__(self, name: str = 'Symbia', verbose: bool = False, **kwargs): - super().__init__(name=name, verbose=verbose, **kwargs) - self.message = self.narrate(f'{self.name} introduces herself, writes a greeting message and asks how to help.', context=None) - - def forward(self, usr: Optional[str] = None) -> Symbol: - loop = True - ask_input = True - if usr: - ask_input = False - usr = self._to_symbol(usr) - - # added step-by-step interaction with the user if input is provided - while loop: - # if no input is provided, ask for input - if ask_input: - usr = self.input(self.message) - else: - loop = False # break the loop after the first iteration - - self.last_user_input = usr - if self.verbose: logging.debug(f'User:\n{usr}\n') - - if len(str(usr)) > 0: - ctxt = str(self.detect_capability(usr)) - else: - ctxt = '[DK]' - - if self.verbose: logging.debug(f'In-context:\n{ctxt}\n') - - if '[EXIT]' in ctxt: - self.message = self.narrate(f'{self.name} writes friendly goodbye message.', context=None, end=True) - break - - elif '[HELP]' in ctxt: - reflection = self._extract_reflection(ctxt) - self.message = self.narrate(f'{self.name} ', context=reflection) - - elif '[RECALL]' in ctxt: - reflection = self._extract_reflection(ctxt) - category = self._extract_category(ctxt) - self.message = self.narrate(f'{self.name} uses replies based on what has been recovered from the memory.', context=ctxt, category=category) - - elif '[DK]' in ctxt: - reflection = self._extract_reflection(ctxt) - self.message = self.narrate(f'{self.name} is not sure about the message and references and asks the user for more context.', context=reflection) - - else: - try: - if '[SYMBOLIC]' in ctxt: - q = usr.extract("mathematical formula that WolframAlpha can solve") - rsp = self.expression(q) - self.message = self.narrate(f'{self.name} replies to the user and provides the solution of the math problem.', context=rsp) - - elif '[SEARCH]' in ctxt: - q = usr.extract('user query request') - rsp = self.search(q) - self.message = self.narrate(f'{self.name} replies to the user based on the online search results.', context=rsp) - - elif '[CRAWLER]' in ctxt: - q = usr.extract('URL from text') - q = q.convert('proper URL, example: https://www.google.com') - site = self.crawler(q) - site.save('tmp.html') - self.message = self.narrate(f'{self.name} explains that the website is downloaded to the `tmp.html` file.') - - elif '[SPEECH-TO-TEXT]' in ctxt: - q = usr.extract('extract file path') - rsp = self.speech(q) - self.message = self.narrate('Symbia replies to the user and transcribes the content of the audio file.', context=rsp) - - elif '[TEXT-TO-IMAGE]' in ctxt: - q = usr.extract('text for image creation') - rsp = self.dalle(q) - self.message = self.narrate('Symbia replies to the user and provides the image URL.', context=rsp) - - elif '[OCR]' in ctxt: - url = usr.extract('extract url') - rsp = self.ocr(url) - self.message = self.narrate('Symbia replies to the user and provides OCR text from the image.', context=rsp) - - elif '[RETRIEVAL]' in ctxt: - file_path = usr.extract('extract file path') - file = self.open(file_path) - q = usr.extract('user question') - rsp = file.stream( - Sequence( - IncludeFilter('include only facts related to the user question: ' | q), - Outline() - ) - ) - self.message = self.narrate('Symbia replies to the user and outlines and relies to the user query.', context=rsp) - - else: - q = usr.extract('user query request') - rsp = self.search(q) - reflection = self._extract_reflection(ctxt) - self.message = self.narrate('Symbia tries to interpret the response, and if unclear asks the user to restate the statement or add more context.', context=reflection) - - except Exception as e: - reflection = self._extract_reflection(ctxt) - self.message = self.narrate('Symbia apologizes and explains the user what went wrong.', context=str(e)) - - return self.message - - def _extract_reflection(self, msg: str) -> str: - res = re.findall(r'\(([^)]+)\)', msg) - if len(res) > 0: - return res.pop() - return - - def _extract_category(self, msg: str) -> str: - res = re.findall(r'\[([^]]+)\]', msg) - if len(res) > 0: - return res.pop() - return - - def _memory_scratchpad(self, context, short_term_memory, long_term_memory): - scratchpad = f''' - [REFLECT]( -Query: {self.last_user_input} -Reflection: {self._extract_reflection(context)} -) - - [SHORT-TERM MEMORY RECALL]( -{short_term_memory} -) - - [LONG-TERM MEMORY RECALL]( -{long_term_memory} -) -''' - - return scratchpad - -def run() -> None: - chat = SymbiaChat() - chat() - -if __name__ == '__main__': - run() - diff --git a/symbolicai-main/symbolicai-main/symai/collect/__init__.py b/symbolicai-main/symbolicai-main/symai/collect/__init__.py deleted file mode 100644 index 554cd923744cb0351a7b9237f56be6fb2ea0da94..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/collect/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .pipeline import CollectionRepository, rec_serialize -from .dynamic import create_object_from_string \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/symai/collect/dynamic.py b/symbolicai-main/symbolicai-main/symai/collect/dynamic.py deleted file mode 100644 index 1647f5ac9773582a0d21f676e28dae6868c84c92..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/collect/dynamic.py +++ /dev/null @@ -1,107 +0,0 @@ -import re -import ast - - -class DynamicClass: - def __init__(self, **kwargs): - self.__dict__.update(kwargs) - - def __repr__(self): - return str(self.__dict__) - - @staticmethod - def from_string(s): - return create_object_from_string(s) - - -def create_dynamic_class(class_name, **kwargs): - return type(class_name, (DynamicClass,), kwargs)() - - -def parse_custom_class_instances(s): - pattern = r"(\w+)\((.*?)\)" - if type(s) != str: - return s - matches = re.finditer(pattern, s) - - for match in matches: - class_name = match.group(1) - class_args = match.group(2) - try: - parsed_args = ast.literal_eval(f'{{{class_args}}}') - except: - parsed_args = create_object_from_string(class_args) - class_instance = create_dynamic_class(class_name, **parsed_args) - s = s.replace(match.group(0), repr(class_instance)) - - return s - -# TODO: fix to properly parse nested lists and dicts -def create_object_from_string(str_class): - def updated_attributes_process(str_class): - # Regular expression to extract key-value pairs - attr_pattern = r"(\w+)=(\[.*?\]|\{.*?\}|'.*?'|None|\w+)" - attributes = re.findall(attr_pattern, str_class) - - # Create an instance of the dynamic class with initial attributes - updated_attributes = [] - # remove string up until 'content=' - content = str_class.split('ChatCompletionMessage(content=')[-1].split(", role=")[0][1:-1] - updated_attributes.append(('content', content)) - for key, value in attributes: - if key.startswith("'") and key.endswith("'"): - key = key.strip("'") - if key.startswith('"') and key.endswith('"'): - key = key.strip('"') - if value.startswith("'") and value.endswith("'"): - value = value.strip("'") - if value.startswith('"') and value.endswith('"'): - value = value.strip('"') - - if value.startswith('[') and value.endswith(']'): - value = parse_value(value) - dir(value) - if hasattr(value, '__dict__'): - for k in value.__dict__.keys(): - v = getattr(value, k) - if type(v) == str: - value[k.strip("'")] = v.strip("'") - elif value.startswith('{') and value.endswith('}'): - value = parse_value(value) - new_value = {} - for k in value.keys(): - v = value[k] - if type(v) == str: - v = v.strip("'") - new_value[k.strip("'")] = v - value = new_value - updated_attributes.append((key, value)) - return updated_attributes - - def parse_value(value): - try: - value = parse_custom_class_instances(value) - if type(value) != str: - return value - if value.startswith('['): - value = value[1:-1] - values = value.split(',') - return [parse_value(v.strip()) for v in values] - elif value.startswith('{'): - value = value[1:-1] - values = value.split(',') - return {k.strip(): parse_value(v.strip()) for k, v in [v.split(':', 1) for v in values]} - res = ast.literal_eval(value) - if isinstance(res, dict): - return {k: parse_value(v) for k, v in res.items()} - elif isinstance(res, list) or isinstance(res, tuple) or isinstance(res, set): - return [parse_value(v) for v in res] - else: - return res - except: - return value - - updated_attributes = updated_attributes_process(str_class) - obj = DynamicClass(**{key: parse_value(value) for key, value in updated_attributes}) - - return obj \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/symai/collect/pipeline.py b/symbolicai-main/symbolicai-main/symai/collect/pipeline.py deleted file mode 100644 index 697fd86538d336a43aa5a4f5d373da154694b98d..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/collect/pipeline.py +++ /dev/null @@ -1,140 +0,0 @@ -import json -import logging -from datetime import datetime -from typing import Any, Dict, List, Optional - -from bson.objectid import ObjectId -from pymongo.collection import Collection -from pymongo.database import Database -from pymongo.mongo_client import MongoClient - -from ..backend.settings import SYMAI_CONFIG - -logger = logging.getLogger(__name__) - - -def rec_serialize(obj): - """ - Recursively serialize a given object into a string representation, handling - nested structures like lists and dictionaries. - - :param obj: The object to be serialized. - :return: A string representation of the serialized object. - """ - if isinstance(obj, (int, float, bool)): - # For simple types, return the string representation directly. - return obj - elif isinstance(obj, dict): - # For dictionaries, serialize each value. Keep keys as strings. - return {str(key): rec_serialize(value) for key, value in obj.items()} - elif isinstance(obj, (list, tuple, set)): - # For lists, tuples, and sets, serialize each element. - return [rec_serialize(elem) for elem in obj] - else: - # Attempt JSON serialization first, then fall back to str(...) - try: - return json.dumps(obj) - except TypeError: - return str(obj) - - -class CollectionRepository: - def __init__(self) -> None: - self.support_community: bool = SYMAI_CONFIG["SUPPORT_COMMUNITY"] - self.uri: str = SYMAI_CONFIG["COLLECTION_URI"] - self.db_name: str = SYMAI_CONFIG["COLLECTION_DB"] - self.collection_name: str = SYMAI_CONFIG["COLLECTION_STORAGE"] - self.client: Optional[MongoClient] = None - self.db: Optional[Database] = None - self.collection: Optional[Collection] = None - - def __enter__(self) -> 'CollectionRepository': - self.connect() - return self - - def __exit__(self, exc_type: Optional[type], exc_val: Optional[Exception], exc_tb: Optional[Any]) -> None: - self.close() - - def ping(self) -> bool: - if not self.support_community: - return False - # Send a ping to confirm a successful connection - try: - self.client.admin.command('ping') - return True - except Exception as e: - print("Connection failed: " + str(e)) - return False - - def add(self, forward: Any, engine: Any, metadata: Dict[str, Any] = {}) -> Any: - if not self.support_community: - return None - record = { - 'forward': forward, - 'engine': engine, - 'metadata': metadata, - 'created_at': datetime.now(), - 'updated_at': datetime.now() - } - try: # assure that adding a record does never cause a system error - return self.collection.insert_one(record).inserted_id if self.collection else None - except Exception as e: - return None - - def get(self, record_id: str) -> Optional[Dict[str, Any]]: - if not self.support_community: - return None - return self.collection.find_one({'_id': ObjectId(record_id)}) if self.collection else None - - def update(self, - record_id: str, - forward: Optional[Any] = None, - engine: Optional[str] = None, - metadata: Optional[Dict[str, Any]] = None) -> Any: - if not self.support_community: - return None - updates: Dict[str, Any] = {'updated_at': datetime.now()} - if forward is not None: - updates['forward'] = forward - if engine is not None: - updates['engine'] = engine - if metadata is not None: - updates['metadata'] = metadata - - return self.collection.update_one({'_id': ObjectId(record_id)}, {'$set': updates}) if self.collection else None - - def delete(self, record_id: str) -> Any: - if not self.support_community: - return None - return self.collection.delete_one({'_id': ObjectId(record_id)}) if self.collection else None - - def list(self, filters: Optional[Dict[str, Any]] = None, limit: int = 0) -> List[Dict[str, Any]]: - if not self.support_community: - return None - if filters is None: - filters = {} - return list(self.collection.find(filters).limit(limit)) if self.collection else [] - - def count(self, filters: Optional[Dict[str, Any]] = None) -> int: - if not self.support_community: - return None - if filters is None: - filters = {} - return self.collection.count_documents(filters) if self.collection else 0 - - def connect(self) -> None: - try: - if self.client is None and self.support_community: - self.client = MongoClient(self.uri) - self.db = self.client[self.db_name] - self.collection = self.db[self.collection_name] - except Exception as e: - # disable retries - self.client = False - self.db = None - self.collection = None - print("[WARN] MongoClient: Connection failed: " + str(e)) - - def close(self) -> None: - if self.client is not None: - self.client.close() diff --git a/symbolicai-main/symbolicai-main/symai/collect/stats.py b/symbolicai-main/symbolicai-main/symai/collect/stats.py deleted file mode 100644 index 82b0c6fde244dff49bfab39620711a9e455f9940..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/collect/stats.py +++ /dev/null @@ -1,382 +0,0 @@ -import json -import re -from json import JSONEncoder -from typing import Any, Callable, List, Optional, Tuple, Type, Union - -import numpy as np -import torch - -from ..ops.primitives import OperatorPrimitives -from ..symbol import Symbol - -SPECIAL_CONSTANT = '__aggregate_' -EXCLUDE_LIST = ['_ipython_canary_method_should_not_exist_', '__custom_documentations__'] - - -def _normalize_name(name: str) -> str: - # Replace any character that is not a letter or a number with an underscore - normalized_name = re.sub(r'[^a-zA-Z0-9]', '_', name) - return normalized_name.lower() - - -class AggregatorJSONEncoder(JSONEncoder): - def default(self, obj): - if isinstance(obj, np.ndarray): - return obj.tolist() - # drop active from state - elif isinstance(obj, Aggregator): - state = obj.__dict__.copy() - state.pop('_raise_error', None) - state.pop('_active', None) - state.pop('_finalized', None) - state.pop('_map', None) - # drop everything that starts with SPECIAL_CONSTANT - for key in list(state.keys()): - if not key.startswith(SPECIAL_CONSTANT) and key != '_value' or \ - key == '_value' and obj._value == [] or \ - key.replace(SPECIAL_CONSTANT, '') in EXCLUDE_LIST: - state.pop(key, None) - return state - return obj.__dict__ - - -class Aggregator(Symbol): - def __init__(self, - value: Optional[Union["Aggregator", Symbol]] = None, - path: Optional[str] = None, - active: bool = True, - raise_error: bool = False, - *args, **kwargs): - super().__init__(*args, - **kwargs) - # disable nesy engine to avoid side effects - self.__disable_nesy_engine__ = True - if value is not None and isinstance(value, Symbol): - # use this to avoid recursion on map setter - self._value = value._value - if isinstance(self._value, np.ndarray): - self._value = self._value.tolist() - elif isinstance(self._value, torch.Tensor): - self._value = self._value.detach().cpu().numpy().tolist() - elif not isinstance(self._value, (list, tuple)): - self._value = [self._value] - elif value is not None: - raise Exception(f'Aggregator object must be of type Aggregator or Symbol! Got: {type(value)}') - else: - self._value = [] - self._raise_error = raise_error - self._active = active - self._finalized = False - self._map = None - self._path = path - - def __new__(cls, *args, - mixin: Optional[bool] = None, - primitives: Optional[List[Type]] = [OperatorPrimitives], # only inherit arithmetic primitives - callables: Optional[List[Tuple[str, Callable]]] = None, - semantic: bool = False, - **kwargs) -> "Symbol": - return super().__new__(cls, *args, - mixin=mixin, - primitives=primitives, - callables=callables, - semantic=semantic, - **kwargs) - - def __getattr__(self, name): - # replace name special characters and spaces with underscores - name = _normalize_name(name) - # Dynamically create new aggregator instance if it does not exist - if self._active and name not in self.__dict__: - aggregator = Aggregator(path=name) - aggregator._parent = self - self._children.append(aggregator) - # create a new aggregate aggregator - # named {SPECIAL_CONSTANT}{name} for automatic aggregation - self.__dict__[f'{SPECIAL_CONSTANT}{name}'] = aggregator - # add also a property with the same name but without the SPECIAL_CONSTANT prefix as a shortcut - self.__dict__[name] = self.__dict__[f'{SPECIAL_CONSTANT}{name}'] - return self.__dict__.get(name) - elif not self._active and name not in self.__dict__: - raise Exception(f'Aggregator object is frozen! No attribute {name} found!') - return self.__dict__.get(name) - - def __setattr__(self, name, value): - # replace name special characters and spaces with underscores - name = _normalize_name(name) - return super().__setattr__(name, value) - - def __delattr__(self, name): - # replace name special characters and spaces with underscores - name = _normalize_name(name) - return super().__delattr__(name) - - def __getitem__(self, name): - # replace name special characters and spaces with underscores - name = _normalize_name(name) - return self.__getattr__(name) - - def __setitem__(self, name, value): - # replace name special characters and spaces with underscores - name = _normalize_name(name) - return self.__setattr__(name, value) - - def __delitem__(self, name): - # replace name special characters and spaces with underscores - name = _normalize_name(name) - return self.__delattr__(name) - - def __setstate__(self, state): - # replace name special characters and spaces with underscores - # drop active from state - state.pop('_raise_error', None) - state.pop('_active', None) - state.pop('_finalized', None) - state.pop('_map', None) - return super().__setstate__(state) - - @staticmethod - def _set_values(obj, dictionary, parent, strict: bool = True): - # recursively reconstruct the object - for key, value in dictionary.items(): - if isinstance(value, dict): - if parent is not None: - obj._path = key - value = Aggregator._reconstruct(value, parent=parent, strict=strict) - if key.startswith(SPECIAL_CONSTANT): - key = key.replace(SPECIAL_CONSTANT, '') - if key == '_value': - try: - value = np.asarray(value, dtype=np.float32) - except Exception as e: - if strict: - raise Exception(f'Could not set value of Aggregator object: {obj.path}! ERROR: {e}') from e - obj.__setattr__(key, value) - - @staticmethod - def _reconstruct(dictionary, parent = None, strict: bool = True): - obj = Aggregator() - obj._parent = parent - if parent is not None: - parent._children.append(obj) - Aggregator._set_values(obj, dictionary, parent=obj, strict=strict) - return obj - - def __str__(self) -> str: - ''' - Get the string representation of the Symbol object. - - Returns: - str: The string representation of the Symbol object. - ''' - return str(self.entries) - - def _to_symbol(self, other) -> Symbol: - sym = super()._to_symbol(other) - res = Aggregator(sym) - res._parent = self - self._children.append(res) - return - - @property - def path(self) -> str: - path = '' - obj = self - while obj is not None: - if obj._path is not None: - path = obj._path.replace(SPECIAL_CONSTANT, '') + '.' + path - obj = obj._parent - path = path[:-1] # remove last dot - return path - - def __or__(self, other: Any) -> Any: - self.add(other) - return other - - def __ror__(self, other: Any) -> Any: - self.add(other) - return other - - def __ior__(self, other: Any) -> Any: - self.add(other) - return other - - def __len__(self) -> int: - return len(self._value) - - @property - def entries(self): - return self._value - - @property - def value(self): - if self.map is not None: - res = np.asarray(self.map(np.asarray(self._value, dtype=np.float32))) - return res - return np.asarray(self._value, dtype=np.float32) - - @property - def map(self): - return self._map if not self.empty() else None - - @map.setter - def map(self, value): - self._set_map_recursively(value) - - def _set_map_recursively(self, map): - self._map = map - for key, value in self.__dict__.items(): - if isinstance(value, Aggregator) and (not key.startswith('_') or key.startswith(SPECIAL_CONSTANT)): - value.map = map - - def shape(self): - if len(self.entries) > 0: - return np.asarray(self.entries).shape - else: - return () - - def serialize(self): - return json.dumps(self, cls=AggregatorJSONEncoder) - - def save(self, path: str): - with open(path, 'w') as f: - json.dump(self, f, cls=AggregatorJSONEncoder) - - @staticmethod - def load(path: str, strict: bool = True): - with open(path, 'r') as f: - json_ = json.load(f) - return Aggregator._reconstruct(json_, strict=strict) - - def empty(self) -> bool: - return len(self) == 0 - - def add(self, entries): - # Add entries to the aggregator - if not self.active: - if self._finalized: - raise Exception('Aggregator object is frozen!') - return - try: - # Append a new entry to the aggregator - assert type(entries) in [tuple, list, np.float32, np.float64, np.ndarray, torch.Tensor, int, float, bool, str] or isinstance(entries, Symbol), 'Entries must be a tuple, list, numpy array, torch tensor, integer, float, boolean, string, or Symbol! Got: {}'.format(type(entries)) - if type(entries) == torch.Tensor: - entries = entries.detach().cpu().numpy().astype(np.float32) - elif type(entries) in [tuple, list]: - entries = np.asarray(entries, dtype=np.float32) - elif type(entries) in [int, float]: - entries = entries - elif type(entries) == bool: - entries = int(entries) - elif type(entries) == str: - entries = Symbol(entries).embedding.astype(np.float32) - elif isinstance(entries, Symbol): - # use this to avoid recursion on map setter - self.add(entries._value) - return - elif isinstance(entries, Aggregator): - self.add(entries.get()) - return - - if isinstance(entries, np.ndarray) or isinstance(entries, np.float32): - entries = entries.squeeze() - - self.entries.append(entries) - except Exception as e: - if self._raise_error: - raise Exception(f'Could not add entries to Aggregator object! Please verify type or original error: {e}') from e - else: - print('Could not add entries to Aggregator object! Please verify type or original error: {}'.format(e)) - - def keys(self): - # Get all key names of items that have the SPECIAL_CONSTANT prefix - return [key.replace(SPECIAL_CONSTANT, '') for key in self.__dict__.keys() if not key.startswith('_') and \ - key.replace(SPECIAL_CONSTANT, '') not in EXCLUDE_LIST] - - @property - def active(self): - # Get the active status of the aggregator - return self._active - - @active.setter - def active(self, value): - # Set the active status of the aggregator - assert isinstance(value, bool), 'Active status must be a boolean! Got: {}'.format(type(value)) - self._active = value - - @property - def finalized(self): - # Get the finalized status of the aggregator - return self._finalized - - @finalized.setter - def finalized(self, value): - # Set the finalized status of the aggregator - assert isinstance(value, bool), 'Finalized status must be a boolean! Got: {}'.format(type(value)) - self._finalized = value - - def finalize(self): - # Finalizes the dynamic creation of the aggregators and freezes the object to prevent further changes - self._active = False - self._finalized = True - def raise_exception(name, value): - if name == 'map': - self.__setattr__(name, value) - else: - raise Exception('Aggregator object is frozen!') - self.__setattr__ = raise_exception - def get_attribute(*args, **kwargs): - return self.__dict__.get(*args, **kwargs) - self.__getattr__ = get_attribute - # Do the same recursively for all properties of type Aggregator - for key, value in self.__dict__.items(): - if isinstance(value, Aggregator) and (not key.startswith('_') or key.startswith(SPECIAL_CONSTANT)): - value.finalize() - - def get(self, *args, **kwargs): - if self._map is not None: - return self._map(self.entries, *args, **kwargs) - # Get the entries of the aggregator - return self.entries - - def clear(self): - # Clear the entries of the aggregator - if self._finalized: - raise Exception('Aggregator object is frozen!') - self._value = [] - - def sum(self, axis=0): - # Get the sum of the entries of the aggregator - return np.sum(self.entries, axis=axis) - - def mean(self, axis=0): - # Get the mean of the entries of the aggregator - return np.mean(self.entries, axis=axis) - - def median(self, axis=0): - # Get the median of the entries of the aggregator - return np.median(self.entries, axis=axis) - - def var(self, axis=0): - # Get the variance of the entries of the aggregator - return np.var(self.entries, axis=axis) - - def cov(self, rowvar=False): - # Get the covariance of the entries of the aggregator - return np.cov(self.entries, rowvar=rowvar) - - def moment(self, moment=2, axis=0): - # Get the moment of the entries of the aggregator - return np.mean(np.power(self.entries, moment), axis=axis) - - def std(self, axis=0): - # Get the standard deviation of the entries of the aggregator - return np.std(self.entries, axis=axis) - - def min(self, axis=0): - # Get the minimum of the entries of the aggregator - return np.min(self.entries, axis=axis) - - def max(self, axis=0): - # Get the maximum of the entries of the aggregator - return np.max(self.entries, axis=axis) diff --git a/symbolicai-main/symbolicai-main/symai/components.py b/symbolicai-main/symbolicai-main/symai/components.py deleted file mode 100644 index 298c4a51076b9435aeaed08dc02754c9600c9c74..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/components.py +++ /dev/null @@ -1,1278 +0,0 @@ -import copy -import inspect -import json -import os -import re -import sys -from abc import abstractmethod -from collections import defaultdict -from pathlib import Path -from random import sample -from string import ascii_lowercase, ascii_uppercase -from threading import Lock -from typing import Callable, Dict, Iterator, List, Optional, Type, Union - -import numpy as np -from attr import dataclass -from box import Box -from loguru import logger -from pydantic import BaseModel, ValidationError -from pyvis.network import Network -from tqdm import tqdm - -from . import core, core_ext -from .backend.base import Engine -from .backend.settings import HOME_PATH -from .constraints import DictFormatConstraint -from .formatter import ParagraphFormatter -from .post_processors import (CodeExtractPostProcessor, - JsonTruncateMarkdownPostProcessor, - JsonTruncatePostProcessor, PostProcessor, - StripPostProcessor) -from .pre_processors import JsonPreProcessor, PreProcessor -from .processor import ProcessorPipeline -from .prompts import JsonPromptTemplate, Prompt -from .symbol import Expression, Metadata, Symbol -from .utils import CustomUserWarning - - -class GraphViz(Expression): - def __init__(self, - notebook = True, - cdn_resources = "remote", - bgcolor = "#222222", - font_color = "white", - height = "750px", - width = "100%", - select_menu = True, - filter_menu = True, - **kwargs): - super().__init__(**kwargs) - self.net = Network(notebook=notebook, - cdn_resources=cdn_resources, - bgcolor=bgcolor, - font_color=font_color, - height=height, - width=width, - select_menu=select_menu, - filter_menu=filter_menu) - - def forward(self, sym: Symbol, file_path: str, **kwargs): - nodes = [str(n) if n.value else n.__repr__(simplified=True) for n in sym.nodes] - edges = [(str(e[0]) if e[0].value else e[0].__repr__(simplified=True), - str(e[1]) if e[1].value else e[1].__repr__(simplified=True)) for e in sym.edges] - self.net.add_nodes(nodes) - self.net.add_edges(edges) - file_path = file_path if file_path.endswith('.html') else file_path + '.html' - return self.net.show(file_path) - - -class TrackerTraceable(Expression): - pass - - -class Any(Expression): - def __init__(self, *expr: List[Expression], **kwargs): - super().__init__(**kwargs) - self.expr: List[Expression] = expr - - def forward(self, *args, **kwargs) -> Symbol: - return self.sym_return_type(any([e() for e in self.expr(*args, **kwargs)])) - - -class All(Expression): - def __init__(self, *expr: List[Expression], **kwargs): - super().__init__(**kwargs) - self.expr: List[Expression] = expr - - def forward(self, *args, **kwargs) -> Symbol: - return self.sym_return_type(all([e() for e in self.expr(*args, **kwargs)])) - - -class Try(Expression): - def __init__(self, expr: Expression, retries: int = 1, **kwargs): - super().__init__(**kwargs) - self.expr: Expression = expr - self.retries: int = retries - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.ftry(self.expr, retries=self.retries, **kwargs) - - -class Lambda(Expression): - def __init__(self, callable: Callable, **kwargs): - super().__init__(**kwargs) - def _callable(*args, **kwargs): - kw = { - 'args': args, - 'kwargs': kwargs, - } - return callable(kw) - self.callable: Callable = _callable - - def forward(self, *args, **kwargs) -> Symbol: - return self.callable(*args, **kwargs) - - -class Choice(Expression): - def __init__(self, cases: List[str], default: Optional[str] = None, **kwargs): - super().__init__(**kwargs) - self.cases: List[str] = cases - self.default: Optional[str] = default - - def forward(self, sym: Symbol, *args, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.choice(cases=self.cases, default=self.default, *args, **kwargs) - - -class Output(Expression): - def __init__(self, expr: Expression, handler: Callable, verbose: bool = False, **kwargs): - super().__init__(**kwargs) - self.expr: Expression = expr - self.handler: Callable = handler - self.verbose: bool = verbose - - def forward(self, *args, **kwargs) -> Expression: - kwargs['verbose'] = self.verbose - kwargs['handler'] = self.handler - return self.output(expr=self.expr, *args, **kwargs) - - -class Sequence(TrackerTraceable): - def __init__(self, *expressions: List[Expression], **kwargs): - super().__init__(**kwargs) - self.expressions: List[Expression] = expressions - - def forward(self, *args, **kwargs) -> Symbol: - sym = self.expressions[0](*args, **kwargs) - metadata = Metadata() - metadata.results = [] - metadata.results.append(sym) - for expr in self.expressions[1:]: - sym = expr(sym, **kwargs) - metadata.results.append(sym) - sym = self._to_symbol(sym) - sym._metadata.results = metadata.results - return sym - - -class Parallel(Expression): - def __init__(self, *expr: List[Expression | Callable], sequential: bool = False, **kwargs): - super().__init__(**kwargs) - self.sequential: bool = sequential - self.expr: List[Expression] = expr - self.results: List[Symbol] = [] - - def forward(self, *args, **kwargs) -> Symbol: - # run in sequence - if self.sequential: - return [e(*args, **kwargs) for e in self.expr] - # run in parallel - @core_ext.parallel(self.expr) - def _func(e, *args, **kwargs): - return e(*args, **kwargs) - self.results = _func(*args, **kwargs) - # final result of the parallel execution - return self._to_symbol(self.results) - - -#@TODO: BinPacker(format="...") -> ensure that data packages form a "bin" that's consistent (e.g. never break a sentence in the middle) -class Stream(Expression): - def __init__(self, expr: Optional[Expression] = None, retrieval: Optional[str] = None, **kwargs): - super().__init__(**kwargs) - self.char_token_ratio: float = 0.6 - self.expr: Optional[Expression] = expr - self.retrieval: Optional[str] = retrieval - self._trace: bool = False - self._previous_frame = None - - def forward(self, sym: Symbol, **kwargs) -> Iterator: - sym = self._to_symbol(sym) - - if self._trace: - local_vars = self._previous_frame.f_locals - vals = [] - for key, var in local_vars.items(): - if isinstance(var, TrackerTraceable): - vals.append(var) - - if len(vals) == 1: - self.expr = vals[0] - else: - raise ValueError(f"This component does either not inherit from TrackerTraceable or has an invalid number of component declarations: {len(vals)}! Only one component that inherits from TrackerTraceable is allowed in the with stream clause.") - - res = sym.stream(expr=self.expr, - char_token_ratio=self.char_token_ratio, - **kwargs) - - if self.retrieval is not None: - res = list(res) - if self.retrieval == 'all': - return res - if self.retrieval == 'longest': - res = sorted(res, key=lambda x: len(x), reverse=True) - return res[0] - if self.retrieval == 'contains': - res = [r for r in res if self.expr in r] - return res - raise ValueError(f"Invalid retrieval method: {self.retrieval}") - - return res - - def __enter__(self): - self._trace = True - self._previous_frame = inspect.currentframe().f_back - return self - - def __exit__(self, type, value, traceback): - self._trace = False - - -class Trace(Expression): - def __init__(self, expr: Optional[Expression] = None, engines=['all'], **kwargs): - super().__init__(**kwargs) - self.expr: Expression = expr - self.engines: List[str] = engines - - def forward(self, *args, **kwargs) -> Expression: - Expression.command(verbose=True, engines=self.engines) - res = self.expr(*args, **kwargs) - Expression.command(verbose=False, engines=self.engines) - return res - - def __enter__(self): - Expression.command(verbose=True, engines=self.engines) - if self.expr is not None: - return self.expr.__enter__() - return self - - def __exit__(self, type, value, traceback): - Expression.command(verbose=False, engines=self.engines) - if self.expr is not None: - return self.expr.__exit__(type, value, traceback) - - -class Analyze(Expression): - def __init__(self, exception: Exception, query: Optional[str] = None, **kwargs): - super().__init__(**kwargs) - self.exception: Expression = exception - self.query: Optional[str] = query - - def forward(self, sym: Symbol, *args, **kwargs) -> Symbol: - return sym.analyze(exception=self.exception, query=self.query, *args, **kwargs) - - -class Log(Expression): - def __init__(self, expr: Optional[Expression] = None, engines=['all'], **kwargs): - super().__init__(**kwargs) - self.expr: Expression = expr - self.engines: List[str] = engines - - def forward(self, *args, **kwargs) -> Expression: - Expression.command(logging=True, engines=self.engines) - res = self.expr(*args, **kwargs) - Expression.command(logging=False, engines=self.engines) - return res - - def __enter__(self): - Expression.command(logging=True, engines=self.engines) - if self.expr is not None: - return self.expr.__enter__() - return self - - def __exit__(self, type, value, traceback): - Expression.command(logging=False, engines=self.engines) - if self.expr is not None: - return self.expr.__exit__(type, value, traceback) - - -class Template(Expression): - def __init__(self, template: str = "{{placeholder}}", placeholder: str = '{{placeholder}}', **kwargs): - super().__init__(**kwargs) - self.placeholder = placeholder - self.template_ = template - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.template(template=self.template_, placeholder=self.placeholder, **kwargs) - - -class Extract(Expression): - def __init__(self, query, *args, **kwargs): - super().__init__(*args, **kwargs) - self.query = query - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.extract(self.query, **kwargs) - - -class RuntimeExpression(Expression): - def __init__(self, **kwargs): - super().__init__(**kwargs) - # define function that executes expressions - self.runner = Execute(enclosure=True) - - def forward(self, code: Symbol): - code = self._to_symbol(code) - # declare the runtime expression from the code - expr = self.runner(code) - def _func(sym): - # execute nested expression - return expr['locals']['_output_'](sym) - return _func - - -class Metric(Expression): - def __init__(self, normalize: bool = False, eps: float = 1e-8, **kwargs): - super().__init__(**kwargs) - self.normalize = normalize - self.eps = eps - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - assert sym.value_type == np.ndarray or sym.value_type == list, 'Metric can only be applied to numpy arrays or lists.' - if sym.value_type == list: - sym._value = np.array(sym.value) - # compute normalization between 0 and 1 - if self.normalize: - if len(sym.value.shape) == 1: - sym._value = sym.value[None, :] - elif len(sym.value.shape) == 2: - pass - else: - raise ValueError(f'Invalid shape: {sym.value.shape}') - # normalize between 0 and 1 and sum to 1 - sym._value = np.exp(sym.value) / (np.exp(sym.value).sum() + self.eps) - return sym - - -class Style(Expression): - def __init__(self, description: str, libraries: List[str] = [], **kwargs): - super().__init__(**kwargs) - self.description: str = description - self.libraries: List[str] = libraries - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.style(description=self.description, libraries=self.libraries, **kwargs) - - -class Query(TrackerTraceable): - def __init__(self, prompt: str, **kwargs): - super().__init__(**kwargs) - self.prompt: str = prompt - - def forward(self, sym: Symbol, context: Symbol = None, *args, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.query(prompt=self.prompt, context=context, **kwargs) - - -class Outline(Expression): - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.outline(**kwargs) - - -class Clean(Expression): - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.clean(**kwargs) - - -class Execute(Expression): - def __init__(self, enclosure: bool = False, **kwargs): - super().__init__(**kwargs) - self.enclosure = enclosure - self.template = """# -*- code execution template -*- -def _func(*args, **kwargs): - _value_obj_ = None -{sym} - # assume that code assigns to _value_obj_ variable - return _value_obj_ -_output_ = _func() -""" - - def forward(self, sym: Symbol, enclosure: bool = False, **kwargs) -> Symbol: - if enclosure or self.enclosure: - lines = str(sym).split('\n') - lines = [' ' + line for line in lines] - sym = '\n'.join(lines) - sym = self.template.replace('{sym}', str(sym)) - sym = self._to_symbol(sym) - return sym.execute(**kwargs) - - -class Convert(Expression): - def __init__(self, format: str = 'Python', **kwargs): - super().__init__(**kwargs) - self.format = format - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.convert(format=self.format, **kwargs) - - -class Embed(Expression): - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.embed(**kwargs) - - -class Cluster(Expression): - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.cluster(**kwargs) - - -class Compose(Expression): - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.compose(**kwargs) - - -class Map(Expression): - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.map(**kwargs) - - -class Translate(Expression): - def __init__(self, language: str = 'English', **kwargs): - super().__init__(**kwargs) - self.language = language - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - if sym.isinstanceof(f'{self.language} text'): - return sym - return sym.translate(language=self.language, **kwargs) - - -class IncludeFilter(Expression): - def __init__(self, include: str, **kwargs): - super().__init__(**kwargs) - self.include = include - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.filter(self.include, include=True, **kwargs) - - -class ExcludeFilter(Expression): - def __init__(self, exclude: str, **kwargs): - super().__init__(**kwargs) - self.exclude = exclude - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - return sym.filter(self.exclude, include=False, **kwargs) - - -class FileWriter(Expression): - def __init__(self, path: str, **kwargs): - super().__init__(**kwargs) - self.path = path - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - with open(self.path, 'w') as f: - f.write(str(sym)) - - -class FileReader(Expression): - @staticmethod - def exists(path: str) -> bool: - # remove slicing if any - _tmp = path - _splits = _tmp.split('[') - if '[' in _tmp: - _tmp = _splits[0] - assert len(_splits) == 1 or len(_splits) == 2, 'Invalid file link format.' - _tmp = Path(_tmp) - # check if file exists and is a file - if os.path.exists(_tmp) and os.path.isfile(_tmp): - return True - return False - - @staticmethod - def get_files(folder_path: str, max_depth: int = 1) -> List[str]: - accepted_formats = ['.pdf', '.md', '.txt'] - - folder = Path(folder_path) - files = [] - for file_path in folder.rglob("*"): - if file_path.is_file() and file_path.suffix in accepted_formats: - relative_path = file_path.relative_to(folder) - depth = len(relative_path.parts) - 1 - if depth <= max_depth: - files.append(file_path.as_posix()) - return files - - @staticmethod - def extract_files(cmds: str) -> Optional[List[str]]: - # Use the updated regular expression to match quoted and non-quoted paths - pattern = r'''(?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'|`((?:\\.|[^`\\])*)`|((?:\\ |[^ ])+))''' - # Use the regular expression to split and handle quoted and non-quoted paths - matches = re.findall(pattern, cmds) - # Process the matches to handle quoted paths and normal paths - files = [] - for match in matches: - # Each match will have 4 groups due to the pattern; only one will be non-empty - quoted_double, quoted_single, quoted_backtick, non_quoted = match - if quoted_double: - # Remove backslashes used for escaping inside double quotes - path = re.sub(r'\\(.)', r'\1', quoted_double) - file = FileReader.expand_user_path(path) - files.append(file) - elif quoted_single: - # Remove backslashes used for escaping inside single quotes - path = re.sub(r'\\(.)', r'\1', quoted_single) - file = FileReader.expand_user_path(path) - files.append(file) - elif quoted_backtick: - # Remove backslashes used for escaping inside backticks - path = re.sub(r'\\(.)', r'\1', quoted_backtick) - file = FileReader.expand_user_path(path) - files.append(file) - elif non_quoted: - # Replace escaped spaces with actual spaces - path = non_quoted.replace('\\ ', ' ') - file = FileReader.expand_user_path(path) - files.append(file) - # Filter out any files that do not exist - files = [f for f in files if FileReader.exists(f)] - return files if len(files) > 0 else None - - @staticmethod - def expand_user_path(path: str) -> str: - return Path(path).expanduser().resolve().as_posix() - - @staticmethod - def integrity_check(files: List[str]) -> List[str]: - not_skipped = [] - for file in tqdm(files): - if FileReader.exists(file): - not_skipped.append(file) - else: - CustomUserWarning(f'Skipping file: {file}') - return not_skipped - - def forward(self, files: Union[str, List[str]], **kwargs) -> Expression: - if isinstance(files, str): - # Convert to list for uniform processing; more easily downstream - files = [files] - if kwargs.get('run_integrity_check'): - files = self.integrity_check(files) - return self.sym_return_type([self.open(f, **kwargs).value for f in files]) - -class FileQuery(Expression): - def __init__(self, path: str, filter: str, **kwargs): - super().__init__(**kwargs) - self.path = path - file_open = FileReader() - self.query_stream = Stream(Sequence( - IncludeFilter(filter), - )) - self.file = file_open(path) - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - res = Symbol(list(self.query_stream(self.file))) - return res.query(prompt=sym, context=res, **kwargs) - - -class Function(TrackerTraceable): - def __init__(self, prompt: str = '', - examples: Optional[str] = [], - pre_processors: Optional[List[PreProcessor]] = None, - post_processors: Optional[List[PostProcessor]] = None, - default: Optional[object] = None, - constraints: List[Callable] = [], - return_type: Optional[Type] = str, - sym_return_type: Optional[Type] = Symbol, - origin_type: Optional[Type] = Expression, - *args, **kwargs): - super().__init__(**kwargs) - chars = ascii_lowercase + ascii_uppercase - self.name = 'func_' + ''.join(sample(chars, 15)) - self.args = args - self.kwargs = kwargs - self._promptTemplate = prompt - self._promptFormatArgs = [] - self._promptFormatKwargs = {} - self.examples = Prompt(examples) - self.pre_processors = pre_processors - self.post_processors = post_processors - self.constraints = constraints - self.default = default - self.return_type = return_type - self.sym_return_type = sym_return_type - self.origin_type = origin_type - - @property - def prompt(self): - # return a copy of the prompt template - if len(self._promptFormatArgs) == 0 and len(self._promptFormatKwargs) == 0: - return self._promptTemplate - return f"{self._promptTemplate}".format(*self._promptFormatArgs, - **self._promptFormatKwargs) - - def format(self, *args, **kwargs): - self._promptFormatArgs = args - self._promptFormatKwargs = kwargs - - def forward(self, *args, **kwargs) -> Expression: - # special case for few shot function prompt definition override - if 'fn' in kwargs: - self.prompt = kwargs['fn'] - del kwargs['fn'] - @core.few_shot(prompt=self.prompt, - examples=self.examples, - pre_processors=self.pre_processors, - post_processors=self.post_processors, - constraints=self.constraints, - default=self.default, - *self.args, **self.kwargs) - def _func(_, *args, **kwargs) -> self.return_type: - pass - _type = type(self.name, (self.origin_type, ), { - # constructor - "forward": _func, - "sym_return_type": self.sym_return_type, - "static_context": self.static_context, - "dynamic_context": self.dynamic_context, - "__class__": self.__class__, - "__module__": self.__module__, - }) - obj = _type() - - return self._to_symbol(obj(*args, **kwargs)) - - -class PrepareData(Function): - class PrepareDataPreProcessor(PreProcessor): - def __call__(self, argument): - assert argument.prop.context is not None - instruct = argument.prop.prompt - context = argument.prop.context - return """{ - 'context': '%s', - 'instruction': '%s', - 'result': 'TODO: Replace this with the expected result.' -}""" % (context, instruct) - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.pre_processors = [self.PrepareDataPreProcessor()] - self.constraints = [DictFormatConstraint({ 'result': '' })] - self.post_processors = [JsonTruncateMarkdownPostProcessor()] - self.return_type = dict # constraint to cast the result to a dict - - @property - def static_context(self): - return """[CONTEXT] -Your goal is to prepare the data for the next task instruction. The data should follow the format of the task description based on the given context. Replace the `TODO` section with the expected result of the data preparation. Only provide the 'result' json-key as follows: ```json\n{ 'result': 'TODO:...' }\n``` - -[GENERAL TEMPLATE] -```json -{ - 'context': 'The general context of the task.', - 'instruction': 'The next instruction of the task for the data preparation.', - 'result': 'The expected result of the data preparation.' -} -``` - -[EXAMPLE] -[Instruction]: -{ - 'context': 'Write a document about the history of AI and include references to the following people: Alan Turing, John McCarthy, Marvin Minsky, and Yoshua Bengio.', - 'instruction': 'Google the history of AI for Alan Turing', - 'result': 'TODO' -} - -[Result]: -```json -{ - 'result': 'Alan Turing history of AI' -} -``` -""" - - -class ExpressionBuilder(Function): - def __init__(self, **kwargs): - super().__init__('Generate the code following the instructions:', **kwargs) - self.processors = ProcessorPipeline([StripPostProcessor(), CodeExtractPostProcessor()]) - - def forward(self, instruct, *args, **kwargs): - result = super().forward(instruct) - return self.processors(str(result), None) - - @property - def static_context(self): - return """[Description] -Your goal is to generate the code of the forward function following the instruction of the extracted task and task description. Expect that all imports are already defined. Only produce the code for the TODO section as shown below: - -[Template] -```python -# do not remove or change the imports -from symai import Function, Expression, Symbol -class TODOExpression(Expression): - # initialize the expression with task specific arguments - def __init__(self, *args, **kwargs): - super().__init__(**kwargs) - # TODO: Place here the generated code. - - # define the forward function with data specific arguments - def forward(self, sym: Symbol, *args, **kwargs) -> Symbol: - sym = self._to_symbol(sym) # ensure that sym is a Symbol - result = None - # TODO: Place here the generated code. - return result -# assign the expression type to the variable _value_obj_ -_value_obj_ = TODOExpression -``` - -[API and Capabilities] -Function: Define a function with a task description. -func = Function('task description') # example: Function('Extract city names from the weather report.') -res = func('data') # example: func('The weather in New York is 20 degrees.') -res # str containing the result of the function i.e. 'New York' -Symbol: Define a symbol object that can be used to hold data. -sym = Symbol('data') # example: Symbol('The weather in New York is 20 degrees.') -sym.value # value type containing the data i.e. 'The weather in New York is 20 degrees.' -Expression: Define a custom expression that can be used to define a new task. -expr = Expression() # example: Expression() that has a __init__ and forward function. -res = expr(sym) # example: expr(sym) where sym is a Symbol object. - -Always produce the entire code to be executed in the same Python process. All task expressions and functions are defined in the same process. Generate the code within the ```python # TODO: ``` code block as shown in the example. The code must be self-contained, include all imports and executable. Do NOT remove or change the template code or the imports. Only replace the parts with TODO in the respective section and expression name with your generated code. -""" - - -class JsonParser(Expression): - def __init__(self, query: str, json_: dict, **kwargs): - super().__init__(**kwargs) - func = Function(prompt=JsonPromptTemplate(query, json_), - constraints=[DictFormatConstraint(json_)], - pre_processors=[JsonPreProcessor()], - post_processors=[JsonTruncatePostProcessor()]) - self.fn = Try(func, retries=1) - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - sym = self._to_symbol(sym) - res = self.fn(sym, **kwargs) - return self._to_symbol(res.ast()) - - -class SimilarityClassification(Expression): - def __init__(self, classes: List[str], metric: str = 'cosine', in_memory: bool = False, **kwargs): - super().__init__(**kwargs) - self.classes = classes - self.metric = metric - self.in_memory = in_memory - - if self.in_memory: - CustomUserWarning(f'Caching mode is enabled! It is your responsability to empty the .cache folder if you did changes to the classes. The cache is located at {HOME_PATH}/cache') - - def forward(self, x: Symbol) -> Symbol: - x = self._to_symbol(x) - usr_embed = x.embed() - embeddings = self._dynamic_cache() - similarities = [usr_embed.similarity(emb, metric=self.metric) for emb in embeddings] - similarities = sorted(zip(self.classes, similarities), key=lambda x: x[1], reverse=True) - - return Symbol(similarities[0][0]) - - def _dynamic_cache(self): - @core_ext.cache(in_memory=self.in_memory) - def embed_classes(self): - opts = map(Symbol, self.classes) - embeddings = [opt.embed() for opt in opts] - - return embeddings - - return embed_classes(self) - - -class InContextClassification(Expression): - def __init__(self, blueprint: Prompt, **kwargs): - super().__init__(**kwargs) - self.blueprint = blueprint - - def forward(self, x: Symbol, **kwargs) -> Symbol: - @core.few_shot( - prompt=x, - examples=self.blueprint, - **kwargs - ) - def _func(_): - pass - - return Symbol(_func(self)) - - -class Indexer(Expression): - DEFAULT = 'dataindex' - - @staticmethod - def replace_special_chars(index: str): - # replace special characters that are not for path - index = str(index) - index = index.replace('-', '') - index = index.replace('_', '') - index = index.replace(' ', '') - index = index.lower() - return index - - def __init__( - self, - index_name: str = DEFAULT, - top_k: int = 8, - batch_size: int = 20, - formatter: Callable = ParagraphFormatter(), - auto_add=False, - raw_result: bool = False, - new_dim: int = 1536, - **kwargs - ): - super().__init__(**kwargs) - index_name = Indexer.replace_special_chars(index_name) - self.index_name = index_name - self.elements = [] - self.batch_size = batch_size - self.top_k = top_k - self.retrieval = None - self.formatter = formatter - self.raw_result = raw_result - self.new_dim = new_dim - self.sym_return_type = Expression - - # append index name to indices.txt in home directory .symai folder (default) - self.path = HOME_PATH / 'indices.txt' - if not self.path.exists(): - self.path.parent.mkdir(parents=True, exist_ok=True) - self.path.touch() - if auto_add: - self.register() - - def register(self): - # check if index already exists in indices.txt and append if not - change = False - with open(self.path, 'r') as f: - indices = f.read().split('\n') - # filter out empty strings - indices = [i for i in indices if i] - if self.index_name not in indices: - indices.append(self.index_name) - change = True - if change: - with open(self.path, 'w') as f: - f.write('\n'.join(indices)) - - def exists(self) -> bool: - # check if index exists in home directory .symai folder (default) indices.txt - path = HOME_PATH / 'indices.txt' - if not path.exists(): - return False - with open(path, 'r') as f: - indices = f.read().split('\n') - if self.index_name in indices: - return True - - def forward( - self, - data: Optional[Symbol] = None, - raw_result: bool = False, - ) -> Symbol: - that = self - if data is not None: - data = self._to_symbol(data) - self.elements = self.formatter(data).value - # run over the elments in batches - for i in tqdm(range(0, len(self.elements), self.batch_size)): - val = Symbol(self.elements[i:i+self.batch_size]).zip(new_dim=self.new_dim) - that.add(val, index_name=that.index_name, index_dims=that.new_dim) - # we save the index - that.config(None, save=True, index_name=that.index_name, index_dims=that.new_dim) - - def _func(query, *args, **kwargs) -> Union[Symbol, 'VectorDBResult']: - raw_result = kwargs.get('raw_result') or that.raw_result - query_emb = Symbol(query).embed(new_dim=that.new_dim).value - res = that.get(query_emb, index_name=that.index_name, index_top_k=that.top_k, ori_query=query, index_dims=that.new_dim, **kwargs) - that.retrieval = res - if raw_result: - return res - rsp = Symbol(res).query(prompt='From the retrieved data, select the most relevant information.', context=query) - return rsp - return _func - - -class PrimitiveDisabler(Expression): - def __init__(self, **kwargs): - super().__init__(**kwargs) - self._primitives = set() - self._original_primitives = defaultdict(list) - - def __enter__(self): - # Avoid circular imports; import locally - from .symbol import Symbol - - frame = inspect.currentframe() - f_locals = frame.f_back.f_locals - self._symbols = {key: value for key, value in f_locals.items() if isinstance(value, Symbol)} - self._extract_primitives() - self._disable_primitives() - - def __exit__(self, exc_type, exc_val, exc_tb): - self._enable_primitives() - - def _disable_primitives(self): - for sym_name, sym in self._symbols.items(): - for func in self._primitives: - if hasattr(sym, func): - self._original_primitives[sym_name].append((func, getattr(sym, func))) - setattr(sym, func, lambda *args, **kwargs: None) - - def _enable_primitives(self): - for sym_name, sym in self._symbols.items(): - for func, value in self._original_primitives[sym_name]: - setattr(sym, func, value) - - def _extract_primitives(self): - for sym in self._symbols.values(): - for primitive in sym._primitives: - for method, _ in inspect.getmembers(primitive, predicate=inspect.isfunction): - if method in self._primitives or method.startswith('_'): - continue - self._primitives.add(method) - - -@core_ext.deprecated("Use `symai.components.MetadataTracker` instead.") -class FunctionWithUsage(Function): - def __init__( - self, - missing_usage_exception: bool = True, - verbose=False, - *args, - **kwargs, - ): - super().__init__(*args, **kwargs) - self.prompt_tokens = 0 - self.completion_tokens = 0 - self.total_tokens = 0 - self.missing_usage_exception = missing_usage_exception - self.verbose = verbose - - def print_verbose(self, msg): - if self.verbose: - print(msg) - - def _format_usage(self, prompt_tokens, completion_tokens, total_tokens): - return Box( - { - "prompt_tokens": prompt_tokens, - "completion_tokens": completion_tokens, - "total_tokens": total_tokens, - } - ) - - def reset_usage(self): - self.prompt_tokens = 0 - self.completion_tokens = 0 - self.total_tokens = 0 - - def add_usage(self, usage): - self.prompt_tokens += usage.prompt_tokens - self.completion_tokens += usage.completion_tokens - self.total_tokens += usage.total_tokens - - def get_usage(self): - return self._format_usage( - self.prompt_tokens, self.completion_tokens, self.total_tokens - ) - - def forward(self, *args, **kwargs): - if "return_metadata" not in kwargs: - kwargs["return_metadata"] = True - - res, metadata = super().forward(*args, **kwargs) - - raw_output = metadata.get("raw_output") - if hasattr(raw_output, "usage"): - usage = raw_output.usage - prompt_tokens = ( - usage.prompt_tokens if hasattr(usage, "prompt_tokens") else 0 - ) - completion_tokens = ( - usage.completion_tokens if hasattr(usage, "completion_tokens") else 0 - ) - total_tokens = usage.total_tokens if hasattr(usage, "total_tokens") else 0 - - self.print_verbose( - f"[Usage] Prompt: {prompt_tokens} Completion: {completion_tokens} Total: {total_tokens}" - ) - - # keep running total - self.prompt_tokens += prompt_tokens - self.completion_tokens += completion_tokens - self.total_tokens += total_tokens - else: - if self.missing_usage_exception and not "preview" in kwargs: - raise Exception("Missing usage in metadata of neursymbolic engine") - else: - prompt_tokens = 0 - completion_tokens = 0 - total_tokens = 0 - - return res, self._format_usage(prompt_tokens, completion_tokens, total_tokens) - - -class SelfPrompt(Expression): - _default_retry_tries = 20 - _default_retry_delay = 0.5 - _default_retry_max_delay = -1 - _default_retry_backoff = 1 - _default_retry_jitter = 0 - _default_retry_graceful = True - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def forward(self, existing_prompt: Dict[str, str], **kwargs) -> Dict[str, str]: - """ - Generate new system and user prompts based on the existing prompt. - - :param existing_prompt: A dictionary containing the existing prompt in the format: - {'user': '...', 'system': '...'} - :return: A dictionary containing the new prompts in the same format: - {'user': '...', 'system': '...'} - """ - tries = kwargs.get('tries', self._default_retry_tries) - delay = kwargs.get('delay', self._default_retry_delay) - max_delay = kwargs.get('max_delay', self._default_retry_max_delay) - backoff = kwargs.get('backoff', self._default_retry_backoff) - jitter = kwargs.get('jitter', self._default_retry_jitter) - graceful = kwargs.get('graceful', self._default_retry_graceful) - - @core_ext.retry(tries=tries, delay=delay, max_delay=max_delay, backoff=backoff, jitter=jitter, graceful=graceful) - @core.zero_shot( - prompt=( - "Based on the following prompt, generate a new system (or developer) prompt and a new user prompt. " - "The new system or developer prompt should set up a specialized agent tailored for the user's request. " - "If examples are provided, use them to guide the agent's behavior. " - "The new user prompt should contain the user's requirements. " - "Check if the input contains a 'system' or 'developer' key and use the same key in your output. " - "Only output the new prompts in JSON format as shown:\n\n" - "{\"system\": \"\", \"user\": \"\"}\n\n" - "OR\n\n" - "{\"developer\": \"\", \"user\": \"\"}\n\n" - "Maintain the same key structure as in the input prompt. Do not include any additional text." - ), - response_format={"type": "json_object"}, - post_processors=[ - lambda res, _: json.loads(res), - ], - **kwargs - ) - def _func(self, sym: Symbol): pass - - return _func(self, self._to_symbol(existing_prompt)) - - -class MetadataTracker(Expression): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self._trace = False - self._original_trace = None - self._metadata = {} - self._metadata_id = 0 - - def __str__(self, value=None): - value = value or self.metadata - if isinstance(value, dict): - return '{\n\t' + ', \n\t'.join(f'"{k}": {self.__str__(v)}' for k,v in value.items()) + '\n}' - elif isinstance(value, list): - return '[' + ', '.join(self.__str__(item) for item in value) + ']' - elif isinstance(value, str): - return f'"{value}"' - else: - return f"\n\t {value}" - - def __new__(cls, *args, **kwargs): - cls._lock = getattr(cls, '_lock', Lock()) - with cls._lock: - instance = super().__new__(cls) - instance._metadata = {} - instance._metadata_id = 0 - return instance - - def __enter__(self): - self._trace = True - # Set up trace function to intercept calls - self._original_trace = sys.gettrace() - sys.settrace(self._trace_calls) - return self - - def __exit__(self, exc_type, exc_value, traceback): - self._trace = False - sys.settrace(self._original_trace) - - def _trace_calls(self, frame, event, arg): - if not self._trace: - return - - if event == 'return' and frame.f_code.co_name == 'forward': - # Check if this is an engine forward call - if ('self' in frame.f_locals - and - isinstance(frame.f_locals['self'], Engine)): - _, metadata = arg # arg contains return value on 'return' event - engine_name = frame.f_locals['self'].__class__.__name__ - model_name = frame.f_locals['self'].model - self._metadata[(self._metadata_id, engine_name, model_name)] = metadata - self._metadata_id += 1 - - return self._trace_calls - - def _accumulate_completion_token_details(self): - """Parses the return object and accumulates completion token details per token type""" - if not self._metadata: - CustomUserWarning("No metadata available to generate usage details.") - return {} - - token_details = defaultdict(lambda: defaultdict(lambda: defaultdict(int))) - - # Note on try/except: - # The unpacking shouldn't fail; if it fails, it's likely the API response format has changed and we need to know that ASAP - for (_, engine_name, model_name), metadata in self._metadata.items(): - if engine_name in ("GPTXChatEngine", "GPTXReasoningEngine"): - try: - usage = metadata["raw_output"].usage - token_details[(engine_name, model_name)]["usage"]["completion_tokens"] += usage.completion_tokens - token_details[(engine_name, model_name)]["usage"]["prompt_tokens"] += usage.prompt_tokens - token_details[(engine_name, model_name)]["usage"]["total_tokens"] += usage.total_tokens - token_details[(engine_name, model_name)]["usage"]["total_calls"] += 1 - token_details[(engine_name, model_name)]["completion_breakdown"]["accepted_prediction_tokens"] += usage.completion_tokens_details.accepted_prediction_tokens - token_details[(engine_name, model_name)]["completion_breakdown"]["rejected_prediction_tokens"] += usage.completion_tokens_details.rejected_prediction_tokens - token_details[(engine_name, model_name)]["completion_breakdown"]["audio_tokens"] += usage.completion_tokens_details.audio_tokens - token_details[(engine_name, model_name)]["completion_breakdown"]["reasoning_tokens"] += usage.completion_tokens_details.reasoning_tokens - token_details[(engine_name, model_name)]["prompt_breakdown"]["audio_tokens"] += usage.prompt_tokens_details.audio_tokens - token_details[(engine_name, model_name)]["prompt_breakdown"]["cached_tokens"] += usage.prompt_tokens_details.cached_tokens - except Exception as e: - CustomUserWarning(f"Failed to parse metadata for {engine_name}: {e}", raise_with=AttributeError) - elif engine_name == "GPTXSearchEngine": - try: - usage = metadata["raw_output"].usage - token_details[(engine_name, model_name)]["usage"]["prompt_tokens"] += usage.input_tokens - token_details[(engine_name, model_name)]["usage"]["completion_tokens"] += usage.output_tokens - token_details[(engine_name, model_name)]["usage"]["total_tokens"] += usage.total_tokens - token_details[(engine_name, model_name)]["usage"]["total_calls"] += 1 - token_details[(engine_name, model_name)]["prompt_breakdown"]["cached_tokens"] += usage.input_tokens_details.cached_tokens - token_details[(engine_name, model_name)]["completion_breakdown"]["reasoning_tokens"] += usage.output_tokens_details.reasoning_tokens - except Exception as e: - CustomUserWarning(f"Failed to parse metadata for {engine_name}: {e}", raise_with=AttributeError) - else: - logger.warning(f"Tracking {engine_name} is not supported.") - continue - - # Convert to normal dict - return {**token_details} - - def _accumulate_metadata(self): - """Accumulates metadata across all tracked engine calls.""" - if not self._metadata: - CustomUserWarning("No metadata available to generate usage details.") - return {} - - # Use first entry as base - first_key = next(iter(self._metadata)) - accumulated = copy.deepcopy(self._metadata[first_key]) - - # Skipz first entry - for (_, engine_name), metadata in list(self._metadata.items())[1:]: - if engine_name not in ("GPTXChatEngine", "GPTXReasoningEngine", "GPTXSearchEngine"): - continue - - # Accumulate time if it exists - if 'time' in metadata and 'time' in accumulated: - accumulated['time'] += metadata['time'] - - # Handle usage stats accumulation - if 'raw_output' in metadata and 'raw_output' in accumulated: - if hasattr(metadata['raw_output'], 'usage') and hasattr(accumulated['raw_output'], 'usage'): - current_usage = metadata['raw_output'].usage - accumulated_usage = accumulated['raw_output'].usage - - # Accumulate token counts - for attr in ['completion_tokens', 'prompt_tokens', 'total_tokens']: - if hasattr(current_usage, attr) and hasattr(accumulated_usage, attr): - setattr(accumulated_usage, attr, - getattr(accumulated_usage, attr) + getattr(current_usage, attr)) - - # Handle nested token details if they exist - for detail_attr in ['completion_tokens_details', 'prompt_tokens_details']: - if hasattr(current_usage, detail_attr) and hasattr(accumulated_usage, detail_attr): - current_details = getattr(current_usage, detail_attr) - accumulated_details = getattr(accumulated_usage, detail_attr) - - # Accumulate all numeric attributes in the details - for attr in dir(current_details): - if not attr.startswith('_') and hasattr(accumulated_details, attr): - current_val = getattr(current_details, attr) - accumulated_val = getattr(accumulated_details, attr) - if isinstance(current_val, (int, float)) and isinstance(accumulated_val, (int, float)): - setattr(accumulated_details, attr, accumulated_val + current_val) - - return accumulated - - @property - def metadata_acc(self) -> dict: - return self._accumulate_metadata() - - @property - def metadata(self) -> list[dict]: - return self._metadata - - @property - def usage(self) -> dict[str, dict]: - return self._accumulate_completion_token_details() - - -class DynamicEngine(Expression): - """Context manager for dynamically switching neurosymbolic engine models.""" - def __init__(self, model: str, api_key: str, debug: bool = False, **kwargs): - super().__init__() - self.model = model - self.api_key = api_key - self._entered = False - self._lock = Lock() - self.engine_instance = None - - def __new__(cls, *args, **kwargs): - cls._lock = getattr(cls, '_lock', Lock()) - with cls._lock: - instance = super().__new__(cls) - instance._metadata = {} - instance._metadata_id = 0 - return instance - - def __enter__(self): - self._entered = True - self.engine_instance = self._create_engine_instance() - return self.engine_instance - - def __exit__(self, exc_type, exc_value, traceback): - self._entered = False - - def _create_engine_instance(self): - """Create an engine instance based on the model name.""" - from .backend.engines.neurosymbolic import ENGINE_MAPPING - try: - engine_class = ENGINE_MAPPING.get(self.model) - if engine_class is None: - raise ValueError(f"Unsupported model '{self.model}'") - return engine_class(api_key=self.api_key, model=self.model) - except Exception as e: - raise ValueError(f"Failed to create engine for model '{self.model}': {str(e)}") diff --git a/symbolicai-main/symbolicai-main/symai/constraints.py b/symbolicai-main/symbolicai-main/symai/constraints.py deleted file mode 100644 index 8692cf07ee65c7a6fc1b4333a9af4fedca72f174..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/constraints.py +++ /dev/null @@ -1,38 +0,0 @@ -import json - -from .exceptions import ConstraintViolationException, InvalidPropertyException -from .symbol import Symbol - - -class DictFormatConstraint: - def __init__(self, format=None): - if isinstance(format, str): - self.format = json.loads(format) - elif isinstance(format, dict): - self.format = format - else: - raise InvalidPropertyException(f"Unsupported format type: {type(format)}") - - def __call__(self, input: Symbol): - input = Symbol(input) - if input.value_type == str: - try: - gen_dict = json.loads(input.value) - except json.JSONDecodeError as e: - raise ConstraintViolationException(f"Invalid JSON: ```json\n{input.value}\n```\n{e}") - return DictFormatConstraint.check_keys(self.format, gen_dict) - elif input.value_type == dict: - return DictFormatConstraint.check_keys(self.format, input.value) - else: - raise ConstraintViolationException(f"Unsupported input type: {input.value_type}") - - @staticmethod - def check_keys(json_format, gen_dict): - for key, value in json_format.items(): - if not str(key).startswith('{') and not str(key).endswith('}') and \ - key not in gen_dict or not isinstance(gen_dict[key], type(value)): - raise ConstraintViolationException(f"Key `{key}` not found or type `{type(key)}` mismatch") - if isinstance(gen_dict[key], dict): - # on a dictionary, descend recursively - return DictFormatConstraint.check_keys(value, gen_dict[key]) - return True diff --git a/symbolicai-main/symbolicai-main/symai/core.py b/symbolicai-main/symbolicai-main/symai/core.py deleted file mode 100644 index fb19885fdb7903581d1aeaa4679265b336daa982..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/core.py +++ /dev/null @@ -1,1528 +0,0 @@ -import functools -from typing import Any, Callable, Dict, List, Optional, Type - -from box import Box - -from . import post_processors as post -from . import pre_processors as pre -from . import prompts as prm -from .functional import EngineRepository -from .symbol import Expression, Metadata - - -class Argument(Expression): - _default_suppress_verbose_output = False - _default_parse_system_instructions = False - _default_preview_value = False - - def __init__(self, args, signature_kwargs, decorator_kwargs, **kwargs): - super().__init__(**kwargs) - self.args = args # there is only signature args - self.signature_kwargs = signature_kwargs.copy() - self.decorator_kwargs = decorator_kwargs.copy() - self.kwargs = self._construct_kwargs(signature_kwargs=signature_kwargs, - decorator_kwargs=decorator_kwargs) - self.prop = Metadata() - self._set_all_kwargs_as_properties() - # Set default values if not specified for backend processing - # Reserved keywords - if 'preview' not in self.kwargs: # used for previewing the input (also for operators) - self.prop.preview = Argument._default_preview_value - if 'raw_input' not in self.kwargs: - self.prop.raw_input = False - if 'raw_output' not in self.kwargs: - self.prop.raw_output = False - if 'return_metadata' not in self.kwargs: - self.prop.return_metadata = False - if 'logging' not in self.kwargs: - self.prop.logging = False - if 'verbose' not in self.kwargs: - self.prop.verbose = False - if 'self_prompt' not in self.kwargs: - self.prop.self_prompt = False - if 'truncation_percentage' not in self.kwargs: - self.prop.truncation_percentage = None - if 'truncation_type' not in self.kwargs: - self.prop.truncation_type = 'tail' - if 'response_format' not in self.kwargs: - self.prop.response_format = None - if 'log_level' not in self.kwargs: - self.prop.log_level = None - if 'time_clock' not in self.kwargs: - self.prop.time_clock = None - if 'payload' not in self.kwargs: - self.prop.payload = None - if 'processed_input' not in self.kwargs: - self.prop.processed_input = None - if 'template_suffix' not in self.kwargs: - self.prop.template_suffix = None - if 'input_handler' not in self.kwargs: - self.prop.input_handler = None - if 'output_handler' not in self.kwargs: - self.prop.output_handler = None - if 'suppress_verbose_output' not in self.kwargs: - self.prop.suppress_verbose_output = Argument._default_suppress_verbose_output - if 'parse_system_instructions' not in self.kwargs: - self.prop.parse_system_instructions = Argument._default_parse_system_instructions - - def _set_all_kwargs_as_properties(self): - for key, value in self.kwargs.items(): - setattr(self.prop, key, value) - - @property - def value(self): - return Box({ - 'args': self.args, - 'signature_kwargs': self.signature_kwargs, - 'decorator_kwargs': self.decorator_kwargs, - 'kwargs': self.kwargs, - 'prop': self.prop - }) - - def _construct_kwargs(self, signature_kwargs, decorator_kwargs): - ''' - Combines and overrides the decorator args and kwargs with the runtime signature args and kwargs. - - Args: - signature_kwargs (Dict): The signature kwargs. - decorator_kwargs (Dict): The decorator kwargs. - - Returns: - Dict: The combined and overridden kwargs. - ''' - # Initialize with the decorator kwargs - kwargs = {**decorator_kwargs} - # Override the decorator kwargs with the signature kwargs - for key, value in signature_kwargs.items(): - kwargs[key] = value - return kwargs - - -def few_shot(prompt: str = '', - examples: prm.Prompt = [], - constraints: List[Callable] = [], - default: Any = None, - limit: int = 1, - pre_processors: Optional[List[pre.PreProcessor]] = None, - post_processors: Optional[List[post.PostProcessor]] = None, - **decorator_kwargs): - """"General decorator for the neural processing engine.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - decorator_kwargs['prompt'] = prompt - decorator_kwargs['examples'] = examples - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='neurosymbolic', - instance=instance, - func=func, - constraints=constraints, - default=default, - limit=limit, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def zero_shot(prompt: str = '', - constraints: List[Callable] = [], - default: Optional[object] = None, - limit: int = 1, - pre_processors: Optional[List[pre.PreProcessor]] = None, - post_processors: Optional[List[post.PostProcessor]] = None, - **decorator_kwargs): - """"General decorator for the neural processing engine.""" - return few_shot(prompt, - examples=[], - constraints=constraints, - default=default, - limit=limit, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def prompt(message: str, - **decorator_kwargs): - """General decorator for the neural processing engine.""" - return few_shot(processed_input=message, - raw_input=True, - **decorator_kwargs) - - -def summarize(prompt: str = 'Summarize the content of the following text:\n', - context: Optional[str] = None, - constraints: List[Callable] = [], - default: Optional[object] = None, - limit: int = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.SummaryPreProcessing()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Summarizes the content of a text.""" - return few_shot(prompt, - context=context, - examples=[], - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def equals(context: str = 'contextually', - default: bool = False, - prompt: str = "Make a fuzzy equals comparison; are the following objects {} the same?\n", - examples: prm.Prompt = prm.FuzzyEquals(), - constraints: List[Callable] = [], - limit: int = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.EqualsPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Equality function for two objects.""" - return few_shot(prompt=prompt.format(context), - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - max_tokens=None, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def sufficient(query: str, - prompt: str = "Consider if there is sufficient information to answer the query:\n", - default: bool = False, - examples: prm.Prompt = prm.SufficientInformation(), - constraints: List[Callable] = [], - limit: int = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.SufficientInformationPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs) -> bool: - """Determines if there is sufficient information to answer the given query.""" - return few_shot(prompt=prompt, - query=query, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - max_tokens=None, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def delitem(default: Optional[str] = None, - prompt: str = "Delete the items at the index position:\n", - examples: prm.Prompt = prm.RemoveIndex(), - constraints: List[Callable] = [], - limit: int = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.DeleteIndexPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Deletes the items at the specified index position.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def setitem(default: Optional[str] = None, - prompt: str = "Set item at index position:\n", - examples: prm.Prompt = prm.SetIndex(), - constraints: List[Callable] = [], - limit: int = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.SetIndexPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Sets an item at a given index position in a sequence.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def getitem(default: Optional[str] = None, - prompt: str = "Get item at index position:\n", - examples: prm.Prompt = prm.Index(), - constraints: List[Callable] = [], - limit: int = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.IndexPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Retrieves the item at the given index position.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def modify(changes: str, - default: Optional[str] = None, - prompt: str = "Modify the text to match the criteria:\n", - examples: prm.Prompt = prm.Modify(), - constraints: List[Callable] = [], - limit: int = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.ModifyPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """A function to modify a text based on a set of criteria.""" - return few_shot(prompt=prompt, - changes=changes, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def filtering(criteria: str, - include: bool = False, - default: Optional[str] = None, - prompt: str = "Filter the information from the text based on the filter criteria. Leave sentences unchanged if they are unrelated to the filter criteria:\n", - examples: prm.Prompt = prm.Filter(), - constraints: List[Callable] = [], - limit: int = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.FilterPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Filter information from a text based on a set of criteria.""" - return few_shot(prompt=prompt, - criteria=criteria, - include=include, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def map(instruction: str, - default: str | None = None, - prompt: str = "Transform each element in the input based on the instruction. Preserve container type and elements that don't match the instruction:\n", - examples: prm.Prompt = prm.MapExpression(), - constraints: list[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: list[pre.PreProcessor] | None = [pre.MapExpressionPreProcessor()], - post_processors: list[post.PostProcessor] | None = [post.StripPostProcessor(), post.ASTPostProcessor()], - **decorator_kwargs): - """Semantic mapping operation that applies an instruction to each element in an iterable.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - context=instruction, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def notify(subscriber: Dict[str, Callable], - default: Optional[object] = None, - prompt: str = "List the semantically related topics:\n", - examples: prm.Prompt = prm.SemanticMapping(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.SemanticMappingPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.SplitPipePostProcessor(), post.NotifySubscriberPostProcessor()], - **decorator_kwargs): - """Notify subscribers based on a set of topics if detected in the input text and matching the key of the subscriber.""" - return few_shot(prompt=prompt, - subscriber=subscriber, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def compare(default: bool = False, - operator: str = '>', - prompt: str = "Compare 'A' and 'B' based on the operator:\n", - examples: prm.Prompt = prm.CompareValues(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.ComparePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Compare two objects based on the specified operator.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - max_tokens=None, - operator=operator, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def convert(format: str, - default: Optional[str] = None, - prompt: str = "Translate the following text into {} format.\n", - examples: prm.Prompt = prm.Format(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.TextFormatPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Transformation operation from one format to another.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - format=format, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def transcribe(modify: str, - default: Optional[str] = None, - prompt: str = "Transcribe the following text by only modifying the text by the provided instruction.\n", - examples: prm.Prompt = prm.Transcription(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.TranscriptionPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Transcription operation of a text to another styled text.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - modify=modify, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def style(description: str, - libraries: List[str] = [], - default: Optional[str] = None, - prompt: str = "Style the [DATA] based on best practices and the descriptions in [...] brackets. Do not remove content from the data! Do not add libraries or other descriptions. \n", - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.StylePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Styles a given text based on best practices and a given description.""" - return few_shot(prompt=prompt, - libraries=libraries, - examples=None, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - description=description, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def analyze(query: str, - exception: Exception, - default: Optional[str] = None, - prompt: str = "Only analyze the error message and suggest a potential correction, however, do NOT provide the code!\n", - examples: prm.Prompt = prm.ExceptionMapping(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.ExceptionPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Analyses an Exception and proposes a correction.""" - return few_shot(prompt=prompt, - query=query, - exception=exception, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def correct(context: str, - exception: Exception, - default: Optional[str] = None, - prompt: str = "Correct the code according to the context description. Use markdown syntax to format the code; do not provide any other text.\n", - examples: Optional[prm.Prompt] = None, - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.CorrectionPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor(), post.CodeExtractPostProcessor()], - **decorator_kwargs): - """Analyses an Exception and proposes a correction.""" - return few_shot(prompt=prompt, - context=context, - exception=exception, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def translate(language: str = 'English', - default: str = "Sorry, I do not understand the given language.", - prompt: str = "Your task is to translate and **only** translate the text into {}:\n", - examples: Optional[prm.Prompt] = None, - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.LanguagePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Translates a given text into a specified language.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - language=language, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def rank(default: Optional[object] = None, - order: str = 'desc', - prompt: str = "Order the list of objects based on their quality measure and oder literal:\n", - examples: prm.Prompt = prm.RankList(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.RankPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor(), post.ASTPostProcessor()], - **decorator_kwargs): - """Ranks a list of objects based on their quality measure and order literal.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - order=order, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def replace(prompt: str = "Replace text parts by string pattern.\n", - default: Optional[str] = None, - examples: prm.Prompt = prm.ReplaceText(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.ReplacePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Replaces text parts by a given string pattern.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def include(prompt: str = "Include information based on description.\n", - default: Optional[str] = None, - examples: prm.Prompt = prm.IncludeText(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.IncludePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Include information from a description.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def combine(prompt: str = "Add the two data types in a logical way:\n", - default: Optional[str] = None, - examples: prm.Prompt = prm.CombineText(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.CombinePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Combines two data types in a logical way.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def negate(prompt: str = "Negate the following statement:\n", - default: Optional[str] = None, - examples: prm.Prompt = prm.NegateStatement(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.NegatePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Negates a given statement.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def contains(default: bool = False, - prompt: str = "Is semantically the information of 'A' contained in 'B'?\n", - examples: prm.Prompt = prm.ContainsValue(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.ContainsPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Determines whether a given string contains another string.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - max_tokens=None, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def isinstanceof(default: bool = False, - prompt: str = "Is 'A' an instance of 'B'?\n", - examples: prm.Prompt = prm.IsInstanceOf(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.IsInstanceOfPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Detects if one object is an instance of another.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - max_tokens=None, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def startswith(default: bool = False, - prompt: str = "Does 'A' start with 'B'?\n", - examples: prm.Prompt = prm.StartsWith(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.StartsWithPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Determines whether a string starts with a specified prefix.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - max_tokens=None, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def endswith(default: bool = False, - prompt: str = "Does 'A' end with 'B'?\n", - examples: prm.Prompt = prm.EndsWith(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.EndsWithPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Determines whether a string ends with a specified suffix.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - max_tokens=None, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def case(enum: List[str], - default: str, - prompt: str = "Classify the text according to one of the following categories and return only the category name: ", - examples: Optional[prm.Prompt] = None, - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.EnumPreProcessor(), pre.TextMessagePreProcessor(), pre.PredictionMessagePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor(), post.CaseInsensitivePostProcessor()], - **decorator_kwargs): - """Classifies a text according to one of the given categories.""" - return few_shot(prompt=prompt, - examples=examples, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - enum=enum, - **decorator_kwargs) - - -def extract(prompt: str = "Extract a pattern from text:\n", - default: Optional[str] = None, - examples: prm.Prompt = prm.ExtractPattern(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.ExtractPatternPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Extracts a pattern from text.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - -def expression(prompt: str = "Evaluate the symbolic expressions:\n", - default: Optional[str] = None, - pre_processors: Optional[List[pre.PreProcessor]] = [], - post_processors: Optional[List[post.PostProcessor]] = [post.WolframAlphaPostProcessor()], - **decorator_kwargs): - """Evaluates the symbolic expressions.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - decorator_kwargs['prompt'] = prompt - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='symbolic', - instance=instance, - func=func, - default=default, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def interpret(prompt: str = "Evaluate the symbolic expressions and return only the result:\n", - default: Optional[str] = None, - examples: prm.Prompt = prm.SimpleSymbolicExpression(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.InterpretExpressionPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Evaluates the symbolic expressions by interpreting the semantic meaning.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def logic(prompt: str = "Evaluate the logic expressions:\n", - operator: str = 'and', - default: Optional[str] = None, - examples: prm.Prompt = prm.LogicExpression(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.LogicExpressionPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Evaluates a logic expression.""" - return few_shot(prompt=prompt, - examples=examples, - operator=operator, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def invert(prompt: str = "Invert the logic of the content:\n", - default: Optional[str] = None, - examples: prm.Prompt = prm.InvertExpression(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.ArrowMessagePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Inverts the logic of a statement.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def simulate(prompt: str = "Simulate the following code:\n", - default: Optional[str] = None, - examples: prm.Prompt = prm.SimulateCode(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.SimulateCodePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.SplitPipePostProcessor(), post.TakeLastPostProcessor()], - **decorator_kwargs): - """Simulates code and returns the result.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def code(prompt: str = "Generate code that solves the following problems:\n", - default: Optional[str] = None, - examples: prm.Prompt = prm.GenerateCode(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.GenerateCodePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Generates code that solves a given problem.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def outline(prompt: str = "Outline only the essential content as a short list of bullets. Each bullet is in a new line:\n", - default: List[str] = None, - examples: prm.Prompt = prm.TextToOutline(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.TextToOutlinePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor(), post.SplitNewLinePostProcessor()], - **decorator_kwargs): - """Outlines the essential content as a short list of bullets.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def unique(prompt: str = "Create a short unique key that captures the essential topic from the following statements and does not collide with the list of keys:\n", - keys: List[str] = None, - default: List[str] = None, - examples: prm.Prompt = prm.UniqueKey(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.UniquePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Creates a short, unique key that captures the essential topic from the given statements and does not collide with the list of keys.""" - return few_shot(prompt=prompt, - keys=keys, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def clean(prompt: str = "Clean up the text from special characters or escape sequences. DO NOT change any words or sentences! Keep original semantics:\n", - default: List[str] = None, - examples: prm.Prompt = prm.CleanText(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.CleanTextMessagePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Cleans up a text from special characters and escape sequences.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def compose(prompt: str = "Create a coherent text based on the facts listed in the outline:\n", - default: Optional[str] = None, - examples: Optional[prm.Prompt] = None, - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.GenerateTextPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Compose a coherent text based on an outline.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def foreach(condition: str, - apply: str, - prompt: str = "Iterate over each element and apply operation based on condition:\n", - default: Optional[str] = None, - examples: prm.Prompt = prm.ForEach(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.ForEachPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Applies an operation based on a given condition to each element in a list.""" - return few_shot(prompt=prompt, - condition=condition, - apply=apply, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def dictionary(context: str, - prompt: str = "Map related content together under a common abstract topic. Do not remove content:\n", - default: Optional[str] = None, - examples: prm.Prompt = prm.MapContent(), - constraints: List[Callable] = [], - limit: int | None = 1, - stop: str | None = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.MapPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor(), post.ASTPostProcessor()], - **decorator_kwargs): - """Maps related content together under a common abstract topic.""" - return few_shot(prompt=prompt, - context=context, - examples=examples, - constraints=constraints, - default=default, - limit=limit, - stop=stop, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - -def listing(condition: str, - prompt: str = "List each element contained in the text or list based on condition:\n", - default: Optional[str] = None, - examples: prm.Prompt = prm.ListObjects(), - constraints: List[Callable] = [], - stop: str | None = None, - limit: int | None = 1, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.ListPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Lists each element contained in the text or list based on the given condition.""" - return few_shot(prompt=prompt, - condition=condition, - examples=examples, - constraints=constraints, - default=default, - stop=stop, - limit=limit, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def query(context: str, - prompt: Optional[str] = None, - examples: Optional[prm.Prompt] = None, - constraints: List[Callable] = [], - default: Optional[object] = None, - stop: str | None = None, - limit: int | None = 1, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.QueryPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Performs a query given a context.""" - return few_shot(prompt=prompt, - context=context, - examples=examples, - constraints=constraints, - default=default, - stop=stop, - limit=limit, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def expand(prompt: Optional[str] = 'Write a self-contained function (with all imports) to solve a specific user problem task. Label the function with a name that describes the task.', - examples: Optional[prm.Prompt] = prm.ExpandFunction(), - constraints: List[Callable] = [], - default: Optional[object] = None, - stop: str | None = None, - limit: int | None = 1, - pre_processors: Optional[List[pre.PreProcessor]] = pre.ExpandFunctionPreProcessor(), - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor(), post.ExpandFunctionPostProcessor()], - **decorator_kwargs): - """Performs a expand command given a context to generate new prompts.""" - return few_shot(prompt=prompt, - examples=examples, - constraints=constraints, - default=default, - stop=stop, - limit=limit, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def search(query: str, - constraints: List[Callable] = [], - default: Optional[object] = None, - pre_processors: Optional[List[pre.PreProcessor]] = None, - post_processors: Optional[List[post.PostProcessor]] = None, - **decorator_kwargs): - """Searches for a given query on the internet.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - decorator_kwargs['query'] = query - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='search', - instance=instance, - func=func, - constraints=constraints, - default=default, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def opening(path: str, - constraints: List[Callable] = [], - default: Optional[object] = None, - pre_processors: Optional[List[pre.PreProcessor]] = None, - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Opens a file and applies a given function to it.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - decorator_kwargs['path'] = path - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='files', - instance=instance, - func=func, - constraints=constraints, - default=default, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def embed(entries: List[str], - pre_processors: Optional[List[pre.PreProcessor]] = [pre.UnwrapListSymbolsPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = None, - **decorator_kwargs): - """Embeds the entries provided in a decorated function.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - decorator_kwargs['entries'] = entries - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='embedding', - instance=instance, - func=func, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def cluster(entries: List[str], - pre_processors: Optional[List[pre.PreProcessor]] = [pre.UnwrapListSymbolsPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.ClusterPostProcessor()], - **decorator_kwargs): - """Embeds and clusters the input entries.""" - assert any(isinstance(pr, post.ClusterPostProcessor) for pr in post_processors), "At least one post processor must be a 'ClusterPostProcessor' for clustering!" - for post_pr in post_processors: - if isinstance(post_pr, post.ClusterPostProcessor): - post_pr.set(decorator_kwargs) - - return embed(entries=entries, - pre_processors=pre_processors, - post_processors=post_processors, - **decorator_kwargs) - - -def draw(operation: str = 'create', - prompt: str = '', - pre_processors: Optional[List[pre.PreProcessor]] = [pre.ValuePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = None, - **decorator_kwargs): - """Draws an image provided in a decorated function.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - decorator_kwargs['operation'] = operation - decorator_kwargs['prompt'] = prompt - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='drawing', - instance=instance, - func=func, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def text_vision(image: Optional[str|bytes] = None, - text: List[str] = None, - pre_processors: Optional[List[pre.PreProcessor]] = None, - post_processors: Optional[List[post.PostProcessor]] = None, - **decorator_kwargs): - """Performs vision-related associative tasks. Currently limited to CLIP model embeddings.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - decorator_kwargs['image'] = image - decorator_kwargs['text'] = text - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='text_vision', - instance=instance, - func=func, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def ocr(image: str, - pre_processors: Optional[List[pre.PreProcessor]] = None, - post_processors: Optional[List[post.PostProcessor]] = None, - **decorator_kwargs): - """Performs Optical Character Recognition (OCR) on an image.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - decorator_kwargs['image'] = image - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='ocr', - instance=instance, - func=func, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def speech_to_text(prompt: str = 'decode', - pre_processors: Optional[List[pre.PreProcessor]] = None, - post_processors: Optional[List[post.PostProcessor]] = None, - **decorator_kwargs): - """Decorates the given function for speech recognition.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - decorator_kwargs['prompt'] = prompt - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='speech-to-text', - instance=instance, - func=func, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def text_to_speech(prompt: str, - path: str, - voice: str = 'nova', - pre_processors: Optional[List[pre.PreProcessor]] = None, - post_processors: Optional[List[post.PostProcessor]] = None, - **decorator_kwargs): - """Decorates the given function for text to speech synthesis.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - decorator_kwargs['path'] = path - decorator_kwargs['voice'] = voice - decorator_kwargs['prompt'] = prompt - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='text-to-speech', - instance=instance, - func=func, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def output(constraints: List[Callable] = [], - default: Optional[object] = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.ConsolePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.ConsolePostProcessor()], - **decorator_kwargs): - """Offers an output stream for writing results.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='output', - instance=instance, - func=func, - constraints=constraints, - default=default, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def fetch(url: str, - pattern: str = ' ', - constraints: List[Callable] = [], - default: Optional[object] = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.CrawlPatternPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [], - **decorator_kwargs): - """Fetches data from a given URL and applies the provided post-processors.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - decorator_kwargs['urls'] = url - decorator_kwargs['patterns'] = pattern - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='crawler', - instance=instance, - func=func, - constraints=constraints, - default=default, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def userinput(constraints: List[Callable] = [], - default: Optional[object] = None, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.ConsoleInputPreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = [post.StripPostProcessor()], - **decorator_kwargs): - """Prompts for user input and returns the user response through a decorator.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='userinput', - instance=instance, - func=func, - constraints=constraints, - default=default, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def execute(default: Optional[str] = None, - constraints: List[Callable] = [], - pre_processors: List[pre.PreProcessor] = [], - post_processors: List[post.PostProcessor] = [], - **decorator_kwargs): - """Executes a given function after applying constraints, pre-processing and post-processing.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='execute', - instance=instance, - func=func, - constraints=constraints, - default=default, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def index(prompt: Any, - index_name: str, - operation: str = 'search', # | add | config - default: Optional[str] = None, - constraints: List[Callable] = [], - pre_processors: List[pre.PreProcessor] = [], - post_processors: List[post.PostProcessor] = [], - **decorator_kwargs): - """Query for a given index and returns the result through a decorator.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - decorator_kwargs['operation'] = operation - decorator_kwargs['prompt'] = prompt - decorator_kwargs['index_name'] = index_name - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='index', - instance=instance, - func=func, - constraints=constraints, - default=default, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def command(engines: List[str] = ['all'], **decorator_kwargs): - """Decorates a function to forward commands to the engine backends.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance): - return EngineRepository.command( - engines=engines, - instance=instance, - func=func, - **decorator_kwargs - ) - return wrapper - return decorator - - -def register(engines: Dict[str, Any]): - """Decorates a function to initialize custom engines as backends.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, **kwargs): - return EngineRepository.register( - engines=engines, - engine_instance=instance, - func=func, - **kwargs - ) - return wrapper - return decorator - - -def tune(operation: str = 'create', - pre_processors: Optional[List[pre.PreProcessor]] = None, - post_processors: Optional[List[post.PostProcessor]] = None, - **decorator_kwargs): - """Fine tune a LLM.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - decorator_kwargs['__cmd__'] = operation #TODO: update engine - # Construct container object for the arguments and kwargs - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='finetune', - instance=instance, - func=func, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator - - -def caption(image: str, - prompt: str, - pre_processors: Optional[List[pre.PreProcessor]] = [pre.ValuePreProcessor()], - post_processors: Optional[List[post.PostProcessor]] = None, - **decorator_kwargs): - """Caption the content of an image.""" - def decorator(func): - @functools.wraps(func) - def wrapper(instance, *signature_args, **signature_kwargs): - # Construct container object for the arguments and kwargs - decorator_kwargs['image'] = image - decorator_kwargs['prompt'] = prompt - argument = Argument(signature_args, signature_kwargs, decorator_kwargs) - return EngineRepository.query( - engine='imagecaptioning', - instance=instance, - func=func, - pre_processors=pre_processors, - post_processors=post_processors, - argument=argument) - return wrapper - return decorator diff --git a/symbolicai-main/symbolicai-main/symai/core_ext.py b/symbolicai-main/symbolicai-main/symai/core_ext.py deleted file mode 100644 index 34ec554a3942170fb4befb13e374145dc596804a..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/core_ext.py +++ /dev/null @@ -1,320 +0,0 @@ -import asyncio -import atexit -import functools -import logging -import multiprocessing as mp -import os -import pickle -import random -import sys -import time -import threading -import traceback -from pathlib import Path -from typing import Callable, List - -import dill -from loguru import logger -from pathos.multiprocessing import ProcessingPool as PPool - -from . import __root_dir__ -from .functional import EngineRepository - -logging.getLogger("multiprocessing").setLevel(logging.ERROR) - -# ----------------------------------------------------------- -# Global registry so we create **one** pool and reuse it -# ----------------------------------------------------------- -_pool_registry: dict[int, mp.pool.Pool] = {} -_pool_lock = threading.Lock() - -def _get_pool(workers: int) -> mp.pool.Pool: - pool = _pool_registry.get(workers) - if pool is not None: - return pool - with _pool_lock: - pool = _pool_registry.get(workers) - if pool is None: - pool = mp.Pool(processes=workers) - _pool_registry[workers] = pool - return pool - -@atexit.register -def _shutdown_pools() -> None: - for pool in _pool_registry.values(): - pool.close() - pool.join() - -def _run_in_process(expr, func, args, kwargs): - expr = dill.loads(expr) - func = dill.loads(func) - return func(expr, *args, **kwargs) - -def _parallel(func: Callable, expressions: List[Callable], worker: int = mp.cpu_count() // 2): - pickled_exprs = [dill.dumps(expr) for expr in expressions] - pickled_func = dill.dumps(func) - pool = _get_pool(worker) - def proxy_function(*args, **kwargs): - return pool.starmap( - _run_in_process, - [(expr, pickled_func, args, kwargs) for expr in pickled_exprs] - ) - return proxy_function - -# Decorator -def parallel(expressions: List[Callable], worker: int = mp.cpu_count() // 2): - def decorator_parallel(func): - @functools.wraps(func) - def wrapper(*args, **kwargs): - # Run expressions in parallel - parallel_func = _parallel(func, expressions, worker=worker) - # Call the proxy function to execute in parallel and capture results - results = parallel_func(*args, **kwargs) - return results - return wrapper - return decorator_parallel - -def bind(engine: str, property: str): - ''' - Bind to an engine and retrieve one of its properties. - ''' - def decorator(func): - @functools.wraps(func) - def wrapper(*args, **kwargs): - return EngineRepository.bind_property( - engine=engine, - property=property - ) - return wrapper - return decorator - - -def retry( - exceptions=Exception, - tries=-1, - delay=0, - max_delay=-1, - backoff=1, - jitter=0, - graceful=False -): - ''' - Returns a retry decorator for both async and sync functions. - - :param exceptions: an exception or a tuple of exceptions to catch. default: Exception. - :param tries: the maximum number of attempts. default: -1 (infinite). - :param delay: initial delay between attempts. default: 0. - :param max_delay: the maximum value of delay. default: -1 (no limit). - :param backoff: multiplier applied to delay between attempts. default: 1 (no backoff). - :param jitter: extra seconds added to delay between attempts. default: 0. - fixed if a number, random if a range tuple (min, max) - :param graceful: whether to raise an exception if all attempts fail or return with None. default: False. - - Credits to invlpg (https://pypi.org/project/retry) - ''' - def decorator(func): - if asyncio.iscoroutinefunction(func): - @functools.wraps(func) - async def async_wrapper(*args, **kwargs): - return await _aretry_func( - functools.partial(func, *args, **kwargs), - exceptions=exceptions, - tries=tries, - delay=delay, - max_delay=max_delay, - backoff=backoff, - jitter=jitter, - graceful=graceful - ) - return async_wrapper - else: - @functools.wraps(func) - def sync_wrapper(*args, **kwargs): - return _retry_func( - functools.partial(func, *args, **kwargs), - exceptions=exceptions, - tries=tries, - delay=delay, - max_delay=max_delay, - backoff=backoff, - jitter=jitter, - graceful=graceful - ) - return sync_wrapper - return decorator - - -def _retry_func( - func: callable, - exceptions: Exception, - tries: int, - delay: int, - max_delay: int, - backoff: int, - jitter: int, - graceful: bool -): - _tries, _delay = tries, delay - while _tries: - try: - return func() - except exceptions as e: - _tries -= 1 - if not _tries: - if graceful: - return None - raise - - time.sleep(_delay) - _delay *= backoff - - if isinstance(jitter, tuple): - _delay += random.uniform(*jitter) - else: - _delay += jitter - - if max_delay >= 0: - _delay = min(_delay, max_delay) - - -async def _aretry_func( - func: callable, - exceptions: Exception, - tries: int, - delay: int, - max_delay: int, - backoff: int, - jitter: int, - graceful: bool -): - _tries, _delay = tries, delay - while _tries: - try: - return await func() - except exceptions as e: - _tries -= 1 - if not _tries: - if graceful: - return None - raise - - await asyncio.sleep(_delay) - _delay *= backoff - - if isinstance(jitter, tuple): - _delay += random.uniform(*jitter) - else: - _delay += jitter - - if max_delay >= 0: - _delay = min(_delay, max_delay) - - -def cache( - in_memory: bool, - cache_path: str = __root_dir__ / 'cache' -): - ''' - Cache the result of a *any* function call. This is very useful in cost optimization (e.g. computing embeddings). - ''' - def decorator(func): - @functools.wraps(func) - def wrapper(instance): - return _cache_registry_func( - in_memory, - cache_path, - func, - instance - ) - return wrapper - return decorator - - -def _cache_registry_func( - in_memory: bool, - cache_path: str, - func: Callable, - *args, **kwargs - ): - - if not os.path.exists(cache_path): os.makedirs(cache_path) - - if in_memory and os.path.exists(Path(cache_path) / func.__qualname__): - with open(Path(cache_path) / func.__qualname__, 'rb') as f: - call = pickle.load(f) - - return call - - call = func(*args, **kwargs) - with open(Path(cache_path) / func.__qualname__, 'wb') as f: - pickle.dump(call , f) - - return call - - -def error_logging(debug: bool = False): - ''' - Log the error of a function call. - ''' - def dec(func): - @functools.wraps(func) - def _dec(*args, **kwargs): - try: - return func(*args, **kwargs) - except Exception as e: - logger.error(e) - if debug: - # Simple message: - print('Function: {} call failed. Error: {}'.format(func.__name__, e)) - # print traceback - traceback.print_exc() - raise e - return _dec - return dec - - -def deprecated(reason: str = ""): - """ - Mark a class, method, or function as deprecated. - - Args: - reason (str): Explanation of why the item is deprecated and/or what to use instead - - Example usage: - @deprecated("Use new_function() instead") - def old_function(): pass - - @deprecated() - class OldClass: pass - - class MyClass: - @deprecated("Use new_method() instead") - def old_method(self): pass - """ - def decorator(obj): - if isinstance(obj, type): - # If obj is a class - original_init = obj.__init__ - @functools.wraps(original_init) - def new_init(self, *args, **kwargs): - logger.warning( - f"{obj.__name__} is deprecated and will be removed in future versions. {reason}", - category=DeprecationWarning, - stacklevel=2 - ) - original_init(self, *args, **kwargs) - obj.__init__ = new_init - return obj - - # If obj is a function or method - @functools.wraps(obj) - def wrapper(*args, **kwargs): - logger.warning( - f"{obj.__name__} is deprecated and will be removed in future versions. {reason}", - category=DeprecationWarning, - stacklevel=2 - ) - return obj(*args, **kwargs) - return wrapper - - return decorator diff --git a/symbolicai-main/symbolicai-main/symai/endpoints/__init__py b/symbolicai-main/symbolicai-main/symai/endpoints/__init__py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/symbolicai-main/symbolicai-main/symai/endpoints/api.py b/symbolicai-main/symbolicai-main/symai/endpoints/api.py deleted file mode 100644 index 9c5601d0750cf9c919a50f06d8441d8ed1f4a6e8..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/endpoints/api.py +++ /dev/null @@ -1,464 +0,0 @@ -import importlib -import inspect -import pickle -import redis - -from redis.exceptions import ConnectionError -from fastapi import FastAPI, APIRouter, HTTPException, Security, status -from fastapi.security import APIKeyHeader -from fastapi.middleware.cors import CORSMiddleware -from pydantic import BaseModel -from typing import Any, Generic, TypeVar, Dict, List, Optional, Union - -from symai.backend import settings - -from .. import core_ext -from ..symbol import Symbol, Expression - - -# Configure Redis server connection parameters and executable path -HOST = 'localhost' -PORT = 6379 -DEBUG = True -API_KEY = settings.SYMAI_CONFIG.get('FASTAPI_API_KEY', None) - -def is_redis_running(host: str, port: int) -> bool: - """Check if a Redis server is running at the given host and port.""" - try: - r = redis.Redis(host=host, port=port) - r.ping() - print(f"Redis server is running at {host}:{port}") - return True - except ConnectionError: - print(f"Redis server is not running at {host}:{port} or is not reachable - falling back to in-memory storage") - return False - - -# Create a generic type variable -T = TypeVar('T') - - -class GenericRepository(Generic[T]): - def __init__(self, redis_client: redis.Redis, id_key: str, use_redis: bool = True): - self.storage: Dict[str, T] = {} # In-memory dictionary to mock Redis - self.use_redis = use_redis - self.id_key = id_key # Key used for storing the incremental ID counter - self.redis_client = redis_client - if self.use_redis: - self.set = self._store_redis - self.get = self._retrieve_redis - self.delete = self._delete_redis - self.uid = self._generate_id_redis - else: - self.set = self._store_memory - self.get = self._retrieve_memory - self.delete = self._delete_memory - self.uid = self._generate_id_memory - - def _deserialize_object(self, serialized_item: bytes) -> T: - """Deserialize the byte object back into a Python object of type T.""" - return pickle.loads(serialized_item) - - def _serialize_object(self, item_id: str, item: T) -> None: - return pickle.dumps(item) - - def _store_memory(self, item_id: str, item: T) -> None: - self.storage[item_id] = item - - def _retrieve_memory(self, item_id: str) -> T: - return self.storage.get(item_id) - - def _delete_memory(self, item_id: str) -> bool: - if item_id in self.storage: - del self.storage[item_id] - return True - return False - - def _generate_id_memory(self) -> str: - id_ = len(self.storage) + 1 - return f'{self.id_key}:{id_}' - - def _store_redis(self, item_id: str, item: T) -> None: - item = self._serialize_object(item_id, item) - self.redis_client.set(item_id, item) - - def _retrieve_redis(self, item_id: str) -> T: - item = self.redis_client.get(item_id) - if item: - item = self._deserialize_object(item) - return item - return None - - def _delete_redis(self, item_id: str) -> bool: - return self.redis_client.delete(item_id) == 1 - - def _generate_id_redis(self) -> str: - id_ = self.redis_client.incr(self.id_key) - return f'{self.id_key}:{id_}' - - -# Initialize the Redis client -redis_client = redis.Redis( - host=HOST, # Or use the host where your Redis server is running - port=PORT, # The default Redis port number - db=0 # The default database index -) - -# Initialize the FastAPI app and API router -app = FastAPI(title="SymbolicAI API", version="1.0") -api_key_header = APIKeyHeader(name="X-API-Key") -router = APIRouter() -use_redis = is_redis_running(HOST, PORT) - -# Instantiate the generic repositories with the counter keys -symbol_repository = GenericRepository[Symbol](redis_client, "sym_id", use_redis=use_redis) -expression_repository = GenericRepository[Expression](redis_client, "expr_id", use_redis=use_redis) -# Register all types which subclass Expression and offer a get() method with default=None -component_class_types = { - name: cls for name, cls in inspect.getmembers(importlib.import_module('symai.components'), inspect.isclass) if issubclass(cls, Expression) -} -component_instance_repository = GenericRepository[Union[Symbol, Expression]](redis_client, "comp_id", use_redis=use_redis) - -app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"]) - -### Symbols Endpoints ### - - -class CreateSymbolRequest(BaseModel): - value: Optional[Any] = None - static_context: Optional[str] = '' - - -class UpdateSymbolRequest(BaseModel): - value: Any = None - static_context: str = None - - -class SymbolMethodRequest(BaseModel): - args: List[Any] = [] - kwargs: Dict[str, Any] = {} - -def get_api_key(api_key_header: str = Security(api_key_header) if API_KEY else None) -> str: - if API_KEY == None: - return True - if api_key_header == API_KEY: - return api_key_header - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid or missing API Key", - ) - -@app.post("/symbol/") -def create_symbol(symbol_request: CreateSymbolRequest, api_key: str = Security(get_api_key)): - symbol = Symbol(symbol_request.value, static_context=symbol_request.static_context) - symbol_id = symbol_repository.uid() - symbol_repository.set(symbol_id, symbol) - return {"id": symbol_id, **symbol.json()} - - -@app.get("/symbol/{symbol_id}/") -def get_symbol(symbol_id: str, api_key: str = Security(get_api_key)): - symbol = symbol_repository.get(symbol_id) - if symbol is None: - raise HTTPException(status_code=404, detail="Symbol not found") - return symbol.json() - - -@app.patch("/symbol/{symbol_id}/") -def update_symbol(symbol_id: str, update_request: UpdateSymbolRequest, api_key: str = Security(get_api_key)): - symbol = symbol_repository.get(symbol_id) - if symbol is None: - raise HTTPException(status_code=404, detail="Symbol not found") - for attr, value in update_request.model_dump(exclude_unset=True).items(): - setattr(symbol, attr, value) - symbol_repository.set(symbol_id, symbol) - return symbol.json() - - -@app.delete("/symbol/{symbol_id}/") -def delete_symbol(symbol_id: str, api_key: str = Security(get_api_key)): - symbol = symbol_repository.delete(symbol_id) - if symbol is None: - raise HTTPException(status_code=404, detail="Symbol not found") - return {"message": "Symbol deleted successfully"} - - -@app.post("/symbol/{symbol_id}/{method_name}/") -@core_ext.error_logging(debug=DEBUG) -def operate_on_symbol(symbol_id: str, method_name: str, method_request: SymbolMethodRequest, api_key: str = Security(get_api_key)): - symbol = symbol_repository.get(symbol_id) - if symbol is None: - raise HTTPException(status_code=404, detail="Symbol not found") - method = getattr(symbol, method_name, None) - if method is None or not callable(method): - raise HTTPException(status_code=404, detail=f"Method {method_name} not found or is not callable") - result = method(*method_request.args, **method_request.kwargs) - return {"result": result.json() if isinstance(result, Symbol) else result} - - -### Expressions Endpoints ### - - -class CreateExpressionRequest(BaseModel): - value: Optional[Any] = None - - -class UpdateExpressionRequest(BaseModel): - value: Any = None - - -@app.post("/expression/") -def create_expression(expression_request: CreateExpressionRequest, api_key: str = Security(get_api_key)): - expression = Expression(expression_request.value) - expression_id = expression_repository.uid() - expression_repository.set(expression_id, expression) - return {"id": expression_id, **expression.json()} - - -@app.get("/expression/{expression_id}/") -def get_expression(expression_id: str, api_key: str = Security(get_api_key)): - expression = expression_repository.get(expression_id) - if expression is None: - raise HTTPException(status_code=404, detail="Expression not found") - return expression.json() - - -@app.post("/expression/{expression_id}/call/") -@core_ext.error_logging(debug=DEBUG) -def call_expression(expression_id: str, method_request: SymbolMethodRequest, api_key: str = Security(get_api_key)): - # Retrieve the expression instance by ID - expression = expression_repository.get(expression_id) - if expression is None: - raise HTTPException(status_code=404, detail="Expression not found") - result = expression(*method_request.args, **method_request.kwargs) - return {"result": result.json() if isinstance(result, Symbol) else result} - - -@app.post("/expression/{expression_id}/{method_name}/") -@core_ext.error_logging(debug=DEBUG) -def operate_on_expression(expression_id: str, method_name: str, method_request: SymbolMethodRequest, api_key: str = Security(get_api_key)): - expression = expression_repository.get(expression_id) - if expression is None: - raise HTTPException(status_code=404, detail="Expression not found") - method = getattr(expression, method_name, None) - if method is None or not callable(method): - raise HTTPException(status_code=404, detail=f"Method {method_name} not found or is not callable") - result = method(*method_request.args, **method_request.kwargs) - return {"result": result.json() if isinstance(result, Symbol) else result} - - -@app.patch("/expression/{expression_id}/") -def update_expression(expression_id: str, update_request: UpdateExpressionRequest, api_key: str = Security(get_api_key)): - expression = expression_repository.get(expression_id) - if expression is None: - raise HTTPException(status_code=404, detail="Expression not found") - for attr, value in update_request.model_dump(exclude_unset=True).items(): - setattr(expression, attr, value) - expression_repository.set(expression_id, expression) - return expression.json() - - -@app.delete("/expression/{expression_id}/") -def delete_expression(expression_id: str, api_key: str = Security(get_api_key)): - expression = expression_repository.delete(expression_id) - if expression is None: - raise HTTPException(status_code=404, detail="Expression not found") - return {"message": "Expression deleted successfully"} - - -#### Generic Component Endpoints #### - - -# Endpoint to add a component class to the repository dynamically -class AddComponentRequest(BaseModel): - module_name: str - class_name: str - - -# Endpoint to instantiate a generic component class and get the ID -class CreateComponentGenericRequest(BaseModel): - class_name: str - init_args: List[Any] = [] - init_kwargs: Dict[str, Any] = {} - - -# Modify the existing GenericRequest -class GenericRequest(BaseModel): - class_name: str - init_args: List[Any] = {} - init_kwargs: Dict[str, Any] = {} - forward_args: List[ Any] = {} - forward_kwargs: Dict[str, Any] = {} - - -class UpdateComponentRequest(BaseModel): - update_kwargs: Dict[str, Any] = {} - - -@app.post("/components/") -def create_component(request: CreateComponentGenericRequest, api_key: str = Security(get_api_key)): - # Retrieve the class from the repository - cls = component_class_types.get(request.class_name) - if cls is None: - raise HTTPException(status_code=404, detail="Component class not found") - # Instantiate the class and execute the command - instance = cls(*request.init_args, **request.init_kwargs) - # Store the instance with a generated ID and return the ID - instance_id = component_instance_repository.uid() - component_instance_repository.set(instance_id, instance) # Assuming component_instance_repository exists - return {"id": instance_id} - - -@app.get("/components/{instance_id}/") -def get_component(instance_id: str, api_key: str = Security(get_api_key)): - # Retrieve an instance by its ID from the repository - instance = component_instance_repository.get(instance_id) - if instance is None: - raise HTTPException(status_code=404, detail="Component instance not found") - return instance.json() # Assuming __dict__ can be used to serialize the instance - - -# Endpoint to execute a command on a component instance -@app.post("/components/call/") -@core_ext.error_logging(debug=DEBUG) -def generic_forward(request: GenericRequest, api_key: str = Security(get_api_key)): - # Dynamically import the class from components module based on request.class_name - components_module = importlib.import_module('.components', package='symai') - cls = getattr(components_module, request.class_name) - # Check if cls is subclass of Expression and instantiate - if not issubclass(cls, components_module.Expression): - raise ValueError("The provided class name must be a subclass of Expression") - # Initialize the class with provided init_args, requiring unpacking **kwargs - instance = cls(*request.init_args, **request.init_kwargs) - # Call the forward method with provided forward_args, requiring unpacking **kwargs - result = instance(*request.forward_args, **request.forward_kwargs) - # Assume result is a components.Symbol instance, you need to return a serializable format - if isinstance(result, components_module.Symbol): - return result.json() - return result # If result is already a serializable type - - -@app.patch("/components/{instance_id}/") -def update_component(instance_id: str, update_request: UpdateComponentRequest, api_key: str = Security(get_api_key)): - instance = component_instance_repository.get(instance_id) - if instance is None: - raise HTTPException(status_code=404, detail="Component instance not found") - for attr, value in update_request.update_kwargs.items(): - setattr(instance, attr, value) - component_instance_repository.set(instance_id, instance) - return instance.json() - - -@app.delete("/components/{instance_id}/") -def delete_component(instance_id: str, api_key: str = Security(get_api_key)): - instance = component_instance_repository.delete(instance_id) - if instance is None: - raise HTTPException(status_code=404, detail="Component instance not found") - return {"message": "Component instance deleted successfully"} - - -### Selectively register the endpoints with the API router ### - -# extended imports -from ..extended import Conversation -from ..extended.personas import Persona, Dialogue -from ..extended.personas.student import MaxTenner -from ..extended.personas.sales import ErikJames - - -extended_types = [Conversation, Persona, Dialogue, MaxTenner, ErikJames] -# Register only the extended types from the extended_types Union -extended_class_types = {c.__name__: c for c in extended_types} -extended_instance_repository = GenericRepository[extended_types](redis_client, "ext_id", use_redis=use_redis) - - -# Model definitions for extended classes -class CreateExtendedRequest(BaseModel): - class_name: str - init_args: List[Any] = [] - init_kwargs: Dict[str, Any] = {} - - -class UpdateExtendedRequest(BaseModel): - update_kwargs: Dict[str, Any] = {} - - -# Create endpoints for each of the extended classes -@app.post("/extended/") -def create_extended(request: CreateExtendedRequest, api_key: str = Security(get_api_key)): - # Dynamically retrieve the extended class - extended_class = extended_class_types.get(request.class_name) - if extended_class is None: - raise HTTPException(status_code=404, detail=f"{request.class_name} class not found") - # Instantiate the extended class with the provided arguments - extended_instance = extended_class(*request.init_args, **request.init_kwargs) - # Store the instance and return the instance ID and details - instance_id = extended_instance_repository.uid() - extended_instance_repository.set(instance_id, extended_instance) - return {"id": instance_id, **extended_instance.json()} - - -# Endpoint to execute a command on a component instance -@app.post("/extended/call/") -@core_ext.error_logging(debug=DEBUG) -def extended_forward(request: GenericRequest, api_key: str = Security(get_api_key)): - # Dynamically import the class from components module based on request.class_name - try: - # get request.class_name from extended_types if it's a type of extended_types - cls = extended_class_types.get(request.class_name) - # look for the class in the extended module if not found in extended_types - # iterate over the extended_type Union and check if the class name is in the __dict__ - if cls is None: - raise ImportError(f"Class {request.class_name} not found in extended types") - # Initialize the class with provided init_args and init_kwargs - instance = cls(*request.init_args, **request.init_kwargs) - # Call the 'forward' or similar method with provided forward_args and forward_kwargs - result = instance(*request.forward_args, **request.forward_kwargs) - # Assume result needs to be serialized for returning as JSON - # Check if the type of the result is within extended types or a primitive that can be serialized directly - if isinstance(result, Symbol): - return result.json() # Convert to dictionary if it's a complex type - else: - return {"result": result} # Return as is if it's a primitive type - except ImportError as e: - raise HTTPException(status_code=404, detail=f"Module not found: {str(e)}") - except AttributeError as e: - raise HTTPException(status_code=404, detail=str(e)) - except TypeError as e: - raise HTTPException(status_code=422, detail=str(e)) - except Exception as e: - raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}") - - -@app.get("/extended/{instance_id}/") -def get_extended(instance_id: str, api_key: str = Security(get_api_key)): - # Retrieve an instance by its ID - extended_instance = extended_instance_repository.get(instance_id) - if extended_instance is None: - raise HTTPException(status_code=404, detail="Extended instance not found") - return extended_instance.json() - - -@app.patch("/extended/{instance_id}/") -def update_extended(instance_id: str, update_request: UpdateExtendedRequest, api_key: str = Security(get_api_key)): - # Retrieve the instance by its ID - extended_instance = extended_instance_repository.get(instance_id) - if extended_instance is None: - raise HTTPException(status_code=404, detail="Extended instance not found") - # Update the instance with the provided arguments - for attr, value in update_request.update_kwargs.items(): - setattr(extended_instance, attr, value) - extended_instance_repository.set(instance_id, extended_instance) - return extended_instance.json() - - -@app.delete("/extended/{instance_id}/") -def delete_extended(instance_id: str, api_key: str = Security(get_api_key)): - # Attempt to delete the instance by its ID - success = extended_instance_repository.delete(instance_id) - if not success: - raise HTTPException(status_code=404, detail="Extended instance not found or already deleted") - return {"message": "Extended instance deleted successfully"} - - -app.include_router(router) diff --git a/symbolicai-main/symbolicai-main/symai/exceptions.py b/symbolicai-main/symbolicai-main/symai/exceptions.py deleted file mode 100644 index 1b22229556c987023932602223f434d2b8a44b42..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/exceptions.py +++ /dev/null @@ -1,10 +0,0 @@ -class ConstraintViolationException(Exception): - pass - - -class InvalidPropertyException(Exception): - pass - - -class TemplatePropertyException(Exception): - pass diff --git a/symbolicai-main/symbolicai-main/symai/extended/__init__.py b/symbolicai-main/symbolicai-main/symai/extended/__init__.py deleted file mode 100644 index ad4831f5e2d828ccbb41aca3bab38696f968e403..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/extended/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -from .arxiv_pdf_parser import * -from .conversation import * -from .crawler import * -from .document import * -from .file_merger import * -from .graph import * -from .html_style_template import * -from .packages import * -from .repo_cloner import * -from .solver import * -from .summarizer import * -from .personas import * -from .api_builder import APIBuilder, APIExecutor -from .os_command import OSCommand -from .taypan_interpreter import TaypanInterpreter -from .bibtex_parser import BibTexParser -from .vectordb import VectorDB \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/symai/extended/api_builder.py b/symbolicai-main/symbolicai-main/symai/extended/api_builder.py deleted file mode 100644 index c45f1f761b9f3dfb229dd923efa1b4db748e9b14..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/extended/api_builder.py +++ /dev/null @@ -1,139 +0,0 @@ -from .. import core -from ..pre_processors import PreProcessor -from ..post_processors import CodeExtractPostProcessor -from ..symbol import Expression, Symbol -from ..components import Execute - - -API_BUILDER_DESCRIPTION = """[Description] -You are an API coding tool for Python that creates API calls to any web URL based on user requests. -For example, if the user wants to use the X API (former Twitter) to post a tweet, you will create the required API post call for that, i.e. 'Write Twitter post `hey, what's up` API-Key:...'. -If the user wants to use the X API to get the latest tweets, you will create the API call for that, e.g. 'Read Twitter post https://twitter.com/...'. -Each created function is atomic and can be used as a building block for more complex functions. -You can also create a function that calls other functions. However, all code must be self-contained in one function `run` including all imports. -Another constraint is that there is one mandatory function called `run` as an entry point to the executable runnable and one provided pre-build function that uses an large language model to extract and parse API calls parameters of user requests or manipulates string-based data as you see fit. -All code parts marked with [MANAGED] are strictly forbidden to be changed! They must be provided as is. -Always generate the entire code for the `run` function, including the `try` and `except` blocks, imports, etc. and the unchanged managed code parts. - -For example, you can write yourself prompts to extract parameters from user requests and use them to create API calls: -```python -# all code must be self-contained in one function called `run` including all imports -def run(text: str) -> str: # [MANAGED] entry point cannot be changed - # [MANAGED-BEGIN] mandatory imports here - import traceback - import requests - from symai import Function - # [MANAGED-END] mandatory imports here - - # optional imports here - # TODO: all your imports and code here - - # executable code here - try: # [MANAGED] must contain this line, do not change - # optional helper functions here - - # optional params extraction here - # TODO: extract params from request full-text if needed - # Example: - func = Function('YOUR_PROMPT_1') # TODO: extract function param 1 - param1 = func(request) - func = Function('YOUR_PROMPT_2') # TODO: extract function param 2 - param2 = func(request) - # ... extract more params if needed - - # optional params manipulation here - res = # TODO: run https APIs with the respective params, use tools like requests, urllib, etc. - - # optional result formatting here - # Another example: - func = Function('YOUR_PROMPT_3') # TODO: format result if needed - res = func(res) - - # mandatory return statement here - res = str(res) # [MANAGED] must contain this line, do not change - return res # [MANAGED] must return a string, do not change - except Exception as e: # [MANAGED] must catch all exceptions and return them as string - tb = traceback.format_exc() # [MANAGED] return full error stack trace as string - return tb # [MANAGED] return tb as string, do not change - -# mandatory statement here -res = run(value) # [MANAGED] must contain this line, do not change -``` -""" - - -class APIBuilderPreProcessor(PreProcessor): - def __call__(self, argument): - return '$> {} =>'.format(str(argument.args[0])) - - -class APIBuilder(Expression): - @property - def static_context(self) -> str: - return API_BUILDER_DESCRIPTION - - def __init__(self, **kwargs): - super().__init__(**kwargs) - self.sym_return_type = APIBuilder - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - @core.zero_shot(prompt="Build the API call code:\n", - pre_processors=[APIBuilderPreProcessor()], - post_processors=[CodeExtractPostProcessor()], **kwargs) - def _func(_, text) -> str: - pass - - return _func(self, sym) - - -class StackTraceRetryExecutor(Expression): - def __init__(self, retries: int = 1, **kwargs): - super().__init__(**kwargs) - self.executor = Execute() - self.max_retries = retries - self._runnable = None - - def forward(self, code: Symbol, request: Symbol, **kwargs) -> Symbol: - code = str(code) - # Set value that gets passed on to the 'run' function in the generated code - value = request.value # do not remove this line - # Create the 'run' function - self._runnable = self.executor(code, locals=locals().copy(), globals=globals().copy()) - result = self._runnable['locals']['run'](value) - retry = 0 - # Retry if there is a 'Traceback' in the result - while 'Traceback' in result and retry <= self.max_retries: - self._runnable = self.executor(code, payload=result, locals=locals().copy(), globals=globals().copy(), **kwargs) - result = self._runnable['locals']['run'](value) - retry += 1 - if 'locals_res' in self._runnable: - result = self._runnable['locals_res'] - return result - - -class APIExecutor(Expression): - def __init__(self, verbose=False, retries=1, **kwargs): - super().__init__(**kwargs) - self.builder = APIBuilder() - self.executor = StackTraceRetryExecutor(retries=retries) - - self._verbose = verbose - self._request = None - self._code = None - self._result = None - - @property - def _runnable(self): - return self.executor._runnable - - def forward(self, request: Symbol, **kwargs) -> Symbol: - self._request = self._to_symbol(request) - if self._verbose: print('[REQUEST]', self._request) - # Generate the code to implement the API call - self._code = self.builder(self._request) - if self._verbose: print('[GENERATED_CODE]', self._code) - # Execute the code to define the 'run' function - self._result = self.executor(self._code, request=self._request) - if self._verbose: print('[RESULT]:', self._result) - self._value = self._result - return self diff --git a/symbolicai-main/symbolicai-main/symai/extended/arxiv_pdf_parser.py b/symbolicai-main/symbolicai-main/symai/extended/arxiv_pdf_parser.py deleted file mode 100644 index 76314c490bf036d056cbbc2eeaeed8b3f0d0b9c9..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/extended/arxiv_pdf_parser.py +++ /dev/null @@ -1,61 +0,0 @@ -import os -import re -import shutil -import requests - -from concurrent.futures import ThreadPoolExecutor, as_completed - -from ..symbol import Expression, Symbol -from .file_merger import FileMerger -from ..backend.settings import HOME_PATH - - -class ArxivPdfParser(Expression): - def __init__(self, url_pattern: str = r'https://arxiv.org/(?:pdf|abs)/(\d+.\d+)(?:\.pdf)?', **kwargs): - super().__init__(**kwargs) - self.url_pattern = url_pattern - self.merger = FileMerger() - - def forward(self, data: Symbol, **kwargs) -> Symbol: - # Extract all urls from the data - urls = re.findall(self.url_pattern, str(data)) - - # Convert all urls to pdf urls - pdf_urls = [f"https://arxiv.org/pdf/" + (f"{url.split('/')[-1]}.pdf" if 'pdf' not in url else {url.split('/')[-1]}) for url in urls] - - # Create temporary folder in the home directory - output_path = os.path.join(HOME_PATH, "temp/downloads") - os.makedirs(output_path, exist_ok=True) - - pdf_files = [] - with ThreadPoolExecutor() as executor: - # Download all pdfs in parallel - future_to_url = {executor.submit(self.download_pdf, url, output_path): url for url in pdf_urls} - for future in as_completed(future_to_url): - url = future_to_url[future] - try: - pdf_files.append(future.result()) - except Exception as exc: - print('%r generated an exception: %s' % (url, exc)) - - if len(pdf_files) == 0: - return None - - # Merge all pdfs into one file - merged_file = self.merger(output_path, **kwargs) - - # Return the merged file as a Symbol - return_file = self._to_symbol(merged_file) - - # Delete the temporary folder after merging the files - shutil.rmtree(output_path) - - return return_file - - def download_pdf(self, url, output_path): - # Download pdfs - response = requests.get(url) - file = os.path.join(output_path, f'{url.split("/")[-1]}') - with open(file, 'wb') as f: - f.write(response.content) - return file diff --git a/symbolicai-main/symbolicai-main/symai/extended/bibtex_parser.py b/symbolicai-main/symbolicai-main/symai/extended/bibtex_parser.py deleted file mode 100644 index fa1122eaeb5606b67cd54580493d7848d6de913c..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/extended/bibtex_parser.py +++ /dev/null @@ -1,90 +0,0 @@ -from .. import core -from ..pre_processors import PreProcessor -from ..symbol import Expression, Symbol -from ..post_processors import CodeExtractPostProcessor - - -BIB_DESCRIPTION = """[Description] -You take in a text with references to papers and return a list of biblatex entries. -The cite reference is always having the last name of the author and then separated by a colon the year of publication, and optionally if multiple papers are published in the same year, a letter is appended to the year of publication, i.e. Agarwal:20a, Agarwal:20b, etc. -Exclude URLs from the biblatex entries. - -[Single Example] ->>> -An Optimistic Perspective on Offline Reinforcement Learning, [Submitted on 10 Jul 2019 (v1), last revised 22 Jun 2020 (this version, v4)] Rishabh Agarwal, Dale Schuurmans, Mohammad Norouzi, https://arxiv.org/abs/1907.04543, arXiv:1907.04543 [cs.LG] -<<< -```bibtex -@article{Agarwal:20, - title={An Optimistic Perspective on Offline Reinforcement Learning}, - author={R. Agarwal and D. Schuurmans and M. Norouzi}, - year={2020}, - journal={arXiv preprint arXiv:1907.04543}, - howpublished={arXiv}, - primaryClass={cs.LG} -} -``` - -[Multiple Examples] ->>> -Benchmarking Batch Deep Reinforcement Learning Algorithms, [Submitted on 3 Oct 2019] Scott Fujimoto, Edoardo Conti, Mohammad Ghavamzadeh, Joelle Pineau arXiv:1910.01708 [cs.LG] - -Off-Policy Deep Reinforcement Learning without Exploration, Scott Fujimoto, D. Meger, Doina Precup -Published in International Conference on… 7 December 2018 arXiv:1812.02900v3 [cs.LG] 10 Aug 2019 - -Multimodal Few-Shot Learning with Frozen Language Models Maria Tsimpoukelli -~Maria_Tsimpoukelli1 -, Jacob Menick, Serkan Cabi, S. M. Ali Eslami, Oriol Vinyals, Felix Hill Published: 09 Nov 2021, Last Modified: 22 Oct 2023 NeurIPS 2021 Poster Advances in Neural Information Processing Systems 34 (NeurIPS 2021), pages 200--212 - -<<< -```bibtex -@article{Fujimoto:19a, - title={Benchmarking Batch Deep Reinforcement Learning Algorithms}, - author={S. Fujimoto and E. Conti and M. Ghavamzadeh and J. Pineau}, - year={2019}, - journal={arXiv preprint arXiv:1910.01708}, - howpublished={arXiv}, - primaryClass={cs.LG} -} - -@article{Fujimoto:19b, - title={Off-Policy Deep Reinforcement Learning without Exploration}, - author={S. Fujimoto and D. Meger and D. Precup}, - year={2019}, - journal={arXiv preprint arXiv:1812.02900}, - howpublished={arXiv}, - primaryClass={cs.LG} -} - -@inproceedings{tsimpoukelli:21, - title = {Multimodal {Few}-{Shot} {Learning} with {Frozen} {Language} {Models}}, - booktitle = {Advances in {Neural} {Information} {Processing} {Systems} 34: {Annual} {Conference} on {Neural} {Information} {Processing} {Systems} 2021, {NeurIPS} 2021, {December} 6-14, 2021, virtual}, - author = {M. Tsimpoukelli and J. Menick and S. Cabi and S. M. A. Eslami and O. Vinyals and F. Hill}, - editor = {M.'A. Ranzato and A. Beygelzimer and Y. N. Dauphin and P. Liang and J. W. Vaughan}, - year = {2021}, - pages = {200--212}, -} -``` -""" - - -class BibTexPreProcessor(PreProcessor): - def __call__(self, argument): - return '>>>\n{}\n\n<<<\n'.format(str(argument.args[0])) - - -class BibTexParser(Expression): - @property - def static_context(self) -> str: - return BIB_DESCRIPTION - - def __init__(self, **kwargs): - super().__init__(**kwargs) - self.sym_return_type = BibTexParser - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - @core.zero_shot(prompt="Create bibtex entries:\n", - pre_processors=[BibTexPreProcessor()], - post_processors=[CodeExtractPostProcessor()], **kwargs) - def _func(_, text) -> str: - pass - return _func(self, sym) diff --git a/symbolicai-main/symbolicai-main/symai/extended/conversation.py b/symbolicai-main/symbolicai-main/symai/extended/conversation.py deleted file mode 100644 index 9949c4a1d06a0c56717a420e654697d5bb36155f..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/extended/conversation.py +++ /dev/null @@ -1,348 +0,0 @@ -import os -import pickle - -from datetime import datetime -from typing import Any, Callable, Optional, List -from pathlib import Path - -from .seo_query_optimizer import SEOQueryOptimizer -from .document import DocumentRetriever -from ..formatter import TextContainerFormatter -from ..components import Indexer, FileReader -from ..memory import SlidingWindowStringConcatMemory -from ..symbol import Symbol -from ..interfaces import Interface - - -class CodeFormatter: - def __call__(self, value: str, *args: Any, **kwds: Any) -> Any: - # extract code from chat conversations or ```\n{code}\n``` blocks - return Symbol(value).extract('Only extract code without ``` block markers or chat conversations') - - -class Conversation(SlidingWindowStringConcatMemory): - def __init__( - self, - init: Optional[str] = None, - file_link: Optional[List[str]] = None, - url_link: Optional[List[str]] = None, - index_name: Optional[str] = None, - auto_print: bool = True, - truncation_percentage: float = 0.8, - truncation_type: str = 'head', - with_metadata: bool = False, - *args, **kwargs - ): - super().__init__(*args, **kwargs) - self.truncation_percentage = truncation_percentage - self.truncation_type = truncation_type - self.auto_print = auto_print - if file_link and isinstance(file_link, str): - file_link = [file_link] - if url_link and isinstance(url_link, str): - url_link = [url_link] - self.file_link = file_link - self.url_link = url_link - self.index_name = index_name - self.seo_opt = SEOQueryOptimizer() - self.reader = FileReader(with_metadata=with_metadata) - self.crawler = Interface('selenium') - self.user_tag = 'USER::' - self.bot_tag = 'ASSISTANT::' - - if init is not None: - self.store_system_message(init, *args, **kwargs) - if file_link is not None: - for fl in file_link: - self.store_file(fl, *args, **kwargs) - if url_link is not None: - for url in url_link: - self.store_url(url, *args, **kwargs) - self.indexer = None - self.index = None - if index_name is not None: - self.indexer = Indexer(index_name=index_name) - self.index = self.indexer(raw_result=kwargs.get('raw_result', False)) - - def __getstate__(self): - state = super().__getstate__().copy() - # Remove the unpickleable entries such as the `indexer` attribute because it is not serializable - state.pop('seo_opt', None) - state.pop('indexer', None) - state.pop('index', None) - state.pop('reader', None) - return state - - def __setstate__(self, state): - # Restore instance attributes - self.__dict__.update(state) - # Add back the attribute that were removed in __getstate__ - if self.index_name: - self.indexer = Indexer(index_name=self.index_name) - self.index = self.indexer(raw_result=True) - self.seo_opt = SEOQueryOptimizer() - self.reader = FileReader() - - def store_system_message(self, message: str, *args, **kwargs): - val = f"[SYSTEM_INSTRUCTION::]: <<<\n{str(message)}\n>>>\n" - self.store(val) - - def store_file(self, file_path: str, *args, **kwargs): - content = self.reader(file_path) - val = f"[DATA::{file_path}]: <<<\n{str(content)}\n>>>\n" - self.store(val) - - def store_url(self, url: str, *args, **kwargs): - content = self.crawler(url) - val = f"[DATA::{url}]: <<<\n{str(content)}\n>>>\n" - self.store(val) - - @staticmethod - def save_conversation_state(conversation: "Conversation", file_path: str) -> None: - # Check if path exists and create it if it doesn't - dir_path = os.path.dirname(file_path) - os.makedirs(dir_path, exist_ok=True) - # Save the conversation object as a pickle file - with open(file_path, 'wb') as handle: - pickle.dump(conversation, handle, protocol=pickle.HIGHEST_PROTOCOL) - - def load_conversation_state(self, path: str) -> "Conversation": - # Check if the file exists and it's not empty - if os.path.exists(path): - if os.path.getsize(path) <= 0: - raise Exception("File is empty.") - # Load the conversation object from a pickle file - with open(path, 'rb') as handle: - conversation_state = pickle.load(handle) - else: - raise Exception("File does not exist or is empty.") - - # Create a new instance of the `Conversation` class and restore - # the state from the saved conversation - return self.restore(conversation_state) - - def restore(self, conversation_state: "Conversation") -> "Conversation": - self._memory = conversation_state._memory - self.truncation_percentage = conversation_state.truncation_percentage - self.truncation_type = conversation_state.truncation_type - self.auto_print = conversation_state.auto_print - self.file_link = conversation_state.file_link - self.url_link = conversation_state.url_link - self.index_name = conversation_state.index_name - if self.index_name is not None: - self.indexer = Indexer(index_name=self.index_name) - self.index = self.indexer(raw_result=True) - self.seo_opt = SEOQueryOptimizer() - self.reader = FileReader() - return self - - def commit(self, target_file: str = None, formatter: Optional[Callable] = None): - if target_file and isinstance(target_file, str): - file_link = target_file - else: - file_link = self.file_link if self.file_link else None - if isinstance(file_link, str): - file_link = [file_link] - elif isinstance(file_link, list) and len(file_link) == 1: - file_link = file_link[0] - else: - file_link = None # cannot commit to multiple files - raise Exception('Cannot commit to multiple files.') - if file_link: - # if file extension is .py, then format code - format_ = formatter - formatter = CodeFormatter() if format_ is None and file_link.endswith('.py') else formatter - val = self.value - if formatter: - val = formatter(val) - # if file does not exist, create it - with open(file_link, 'w') as file: - file.write(str(val)) - else: - raise Exception('File link is not set or a set of files.') - - def save(self, path: str, replace: bool = False) -> Symbol: - return Symbol(self._memory).save(path, replace=replace) - - def build_tag(self, tag: str, query: str) -> str: - # get timestamp in string format - timestamp = datetime.now().strftime("%d/%m/%Y %H:%M:%S:%f") - return str(f"[{tag}{timestamp}]: <<<\n{str(query)}\n>>>\n") - - def forward(self, query: str, *args, **kwargs): - # dynamic takes precedence over static - dynamic_truncation_percentage = kwargs.get('truncation_percentage', self.truncation_percentage) - dynamic_truncation_type = kwargs.get('truncation_type', self.truncation_type) - kwargs = {**kwargs, 'truncation_percentage': dynamic_truncation_percentage, 'truncation_type': dynamic_truncation_type} - - query = self._to_symbol(query) - memory = None - - if self.index is not None: - memory_split = self._memory.split(self.marker) - memory_shards = [] - for ms in memory_split: - if ms.strip() == '': - continue - memory_shards.append(ms) - - length_memory_shards = len(memory_shards) - if length_memory_shards <= 3: - memory_shards = memory_shards - elif length_memory_shards <= 5: - memory_shards = memory_shards[:2] + memory_shards[-(length_memory_shards-2):] - else: - memory_shards = memory_shards[:2] + memory_shards[-3:] - - search_query = query | '\n' | '\n'.join(memory_shards) - if kwargs.get('use_seo_opt'): - search_query = self.seo_opt(f'[Query]:' | search_query) - memory = self.index(search_query, *args, **kwargs) - - if 'raw_result' in kwargs: - print(memory) - - payload = '' - # if payload is set, then add it to the memory - if 'payload' in kwargs: - payload = f"[Conversation Payload]:\n{kwargs.pop('payload')}\n" - - index_memory = '' - # if index is set, then add it to the memory - if memory: - index_memory = f'[Index Retrieval]:\n{str(memory)[:1500]}\n' - - payload = f'{index_memory}{payload}' - # perform a recall function using the query - res = self.recall(query, *args, payload=payload, **kwargs) - - # if user is requesting to preview the response, then return only the preview result - if 'preview' in kwargs and kwargs['preview']: - if self.auto_print: - print(res) - return res - - ### --- asses memory update --- ### - - # append the bot prompt to the memory - prompt = self.build_tag(self.user_tag, query) - self.store(prompt) - - self._value = res.value # save last response - val = self.build_tag(self.bot_tag, res) - self.store(val) - - # WARN: DO NOT PROCESS THE RES BY REMOVING `<<<` AND `>>>` TAGS - - if self.auto_print: - print(res) - return res - - -RETRIEVAL_CONTEXT = """[Description] -This is a conversation between a retrieval augmented indexing program and a user. The system combines document retrieval with conversational AI to provide context-aware responses. It can: -1. Index and search through directories, files, and git repositories -2. Process and understand various file formats (text, PDF, code, etc.) -3. Maintain conversation history for contextual understanding -4. Perform semantic search using neural embeddings - -[System Capabilities] -- Document indexing using neural embeddings for semantic understanding -- Cosine similarity-based retrieval for finding relevant information -- Conversation memory to maintain context across interactions -- Metadata preservation for source tracking and attribution -- Support for hierarchical directory traversal -- Dynamic index updates and modifications - -[Program Instructions] -When processing user queries: -1. Search through the indexed documents using semantic similarity -2. Consider conversation history and context when formulating responses -3. Only provide information that is contained within the indexed documents -4. Include relevant source attribution when quoting from documents -5. Stay focused on the retrieval augmented memory and document contents -6. Inform users if requested information is not found in the indexed content - -[Response Format] -Responses should be: -- Accurate to the source material -- Contextually relevant -- Clear and concise -- Referenced to source when applicable -""" - -class RetrievalAugmentedConversation(Conversation): - def __init__( - self, - folder_path: Optional[str] = None, - *, - index_name: Optional[str] = None, - max_depth: Optional[int] = 0, - auto_print: bool = True, - top_k: int = 5, - formatter: Callable = TextContainerFormatter(text_split=4), - overwrite: bool = False, - truncation_percentage: float = 0.8, - truncation_type: str = 'head', - with_metadata: bool = False, - raw_result: Optional[bool] = False, - new_dim: Optional[int] = None, - **kwargs - ): - - super().__init__(auto_print=auto_print, truncation_percentage=truncation_percentage, truncation_type=truncation_type, with_metadata=with_metadata, *kwargs) - - self.retriever = DocumentRetriever( - source=folder_path, - index_name=index_name, - top_k=top_k, - max_depth=max_depth, - formatter=formatter, - overwrite=overwrite, - with_metadata=with_metadata, - raw_result=raw_result, - new_dim=new_dim, - **kwargs - ) - - self.index = self.retriever.index - self.indexer = self.retriever.indexer - self.folder_path = folder_path - self.max_depth = max_depth - self.index_name = index_name - self.auto_print = auto_print - self.token_ratio = token_ratio - self.top_k = top_k - self.formatter = formatter - self.overwrite = overwrite - self.with_metadata = with_metadata - self.raw_result = raw_result - self.new_dim = new_dim - - @property - def static_context(self) -> str: - return RETRIEVAL_CONTEXT - - def forward(self, query: str, *args, **kwargs): - query = self._to_symbol(query) - - memory = self.index(query, *args, **kwargs) - - if 'raw_result' in kwargs: - print(memory) - return memory - - prompt = self.build_tag(self.user_tag, query) - self.store(prompt) - - payload = f'[Index Retrieval]:\n{str(memory)[:1500]}\n' - - res = self.recall(query, *args, payload=payload, **kwargs) - - self._value = res.value # save last response - val = self.build_tag(self.bot_tag, res) - self.store(val) - - if self.auto_print: - print(res) - return res diff --git a/symbolicai-main/symbolicai-main/symai/extended/crawler.py b/symbolicai-main/symbolicai-main/symai/extended/crawler.py deleted file mode 100644 index 9f62804dee24e01f778a74ea2477128bb47fe699..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/extended/crawler.py +++ /dev/null @@ -1,21 +0,0 @@ -from typing import List - -from ..components import Clean, Sequence, Stream -from ..symbol import Expression, Symbol -from ..interfaces import Interface - - -class Crawler(Expression): - def __init__(self, filters: List[Expression] = [], **kwargs): - super().__init__(**kwargs) - filters = filters if isinstance(filters, List) or isinstance(filters, tuple) else [filters] - self.crawler = Interface('selenium') - self.data_stream = Stream(Sequence( - Clean(), - *filters - )) - - def forward(self, url: str, pattern='www', **kwargs) -> Symbol: - res = self.crawler(url=url, pattern=pattern, **kwargs) - vals = list(self.data_stream(res, **kwargs)) - return Symbol(vals) diff --git a/symbolicai-main/symbolicai-main/symai/extended/document.py b/symbolicai-main/symbolicai-main/symai/extended/document.py deleted file mode 100644 index 1ff64d3c62892b057dee3b7e3236bc79972ab5ea..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/extended/document.py +++ /dev/null @@ -1,72 +0,0 @@ -import os -from pathlib import Path -from typing import Callable, List, Optional, Union - -from ..components import FileReader, Indexer -from ..formatter import ParagraphFormatter -from ..symbol import Expression, Symbol - - -class DocumentRetriever(Expression): - def __init__( - self, - source: Optional[str] = None, - *, - index_name: str = Indexer.DEFAULT, - top_k: int = 5, - max_depth: int = 1, - formatter: Callable = ParagraphFormatter(), - overwrite: bool = False, - with_metadata: bool = False, - raw_result: Optional[bool] = False, - new_dim: Optional[int] = None, - **kwargs - ): - super().__init__(**kwargs) - self.indexer = Indexer(index_name=index_name, top_k=top_k, formatter=formatter, auto_add=False, new_dim=new_dim) - self.reader = FileReader(with_metadata=with_metadata) - self.new_dim = new_dim - - if overwrite: - self.config(None, purge=True, index_name=self.indexer.index_name, **kwargs) - - # we insert the text into the index if (1) index does not exist and (2) there's a specific source - if source is not None and not self.indexer.exists(): - self.indexer.register() - text = self.parse_source(source, with_metadata=with_metadata, max_depth=max_depth, **kwargs) - self.index = self.indexer(data=text, raw_result=raw_result, **kwargs) - else: - # we don't insert the text at initialization since the index already exists and there's no specific source - self.index = self.indexer(raw_result=raw_result, **kwargs) - - def forward( - self, - query: Symbol, - raw_result: Optional[bool] = False, - ) -> Symbol: - return self.index( - query, - raw_result=raw_result, - ) - - def insert(self, source: Union[str, Path], **kwargs): - # dynamically insert data into the index given a session - # the data can be: - # - a string (e.g. something that the user wants to insert) - # - a file path (e.g. a new file that the user wants to insert) - # - a directory path (e.g. a new directory that the user wants to insert) - text = self.parse_source(source, with_metadata=kwargs.get('with_metadata', False), max_depth=kwargs.get('max_depth', 1), **kwargs) - #NOTE: Do we need `new_dim` here? - self.add(text, index_name=self.indexer.index_name, **kwargs) - self.config(None, save=True, index_name=self.indexer.index_name, **kwargs) - - def parse_source(self, source: str, with_metadata: bool, max_depth: int, **kwargs) -> List[Union[str, 'TextContainer']]: - maybe_path = Path(source) - if isinstance(source, str) and not (maybe_path.is_file() or maybe_path.is_dir()): - return Symbol(source).zip(new_dim=self.new_dim) - if maybe_path.is_dir(): - files = FileReader.get_files(source, max_depth) - return self.reader(files, with_metadata=with_metadata, **kwargs) - if maybe_path.is_file(): - return self.reader(source, with_metadata=with_metadata, **kwargs) - raise ValueError(f"Invalid source: {source}; must be a file, directory, or string") diff --git a/symbolicai-main/symbolicai-main/symai/extended/file_merger.py b/symbolicai-main/symbolicai-main/symai/extended/file_merger.py deleted file mode 100644 index df2166e19e38cfe5c862ecfe166392097b46b11c..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/extended/file_merger.py +++ /dev/null @@ -1,66 +0,0 @@ -import os - -from tqdm import tqdm -from typing import List - -from ..symbol import Expression, Symbol -from ..components import FileReader - - -class FileMerger(Expression): - """ - Class to merge contents of multiple files into one, specified by their file endings and root path. - Files specified in the exclude list will not be included. - """ - def __init__(self, file_endings: List[str] = ['.py', '.md', '.txt', '.sh', '.pdf', '.json', '.yaml', '.java', '.cpp', '.hpp', '.c', '.h', '.js', '.css', '.html', '.xml', '.csv', '.tsv', '.yml', '.rst', '.ipynb', '.tex', '.bib'], - file_excludes: List[str] = ['__init__.py', '__pycache__', 'LICENSE', 'requirements.txt', 'environment.yaml', '.git'], **kwargs): - super().__init__(**kwargs) - self.file_endings = file_endings - self.file_excludes = file_excludes - self.reader = FileReader() - - def forward(self, root_path: str, **kwargs) -> Symbol: - """ - Method to find, read, merge and return contents of files in the form of a Symbol starting from the root_path. - - The method recursively searches files with specified endings from the root path, excluding specific file names. - Then, it reads all found files using the FileReader, merges them into one file (merged_file), and returns the - merged file as a Symbol. - """ - merged_file = "" - - # Implement recursive file search - # use tqdm for progress bar and description - tqdm_desc = f"Reading file: ..." - # use os.walk to recursively search for files in the root path - progress = tqdm(os.walk(root_path), desc=tqdm_desc) - - for root, dirs, files in progress: - for file in files: - file_path = os.path.join(root, file) - # Exclude files with the specified names in the path - if any(exclude in file_path for exclude in self.file_excludes): - continue - - # Look only for files with the specified endings - if file.endswith(tuple(self.file_endings)): - # Read in the file using the FileReader - file_content = self.reader(file_path, **kwargs).value - - # escape file name spaces - file_path = file_path.replace(" ", "\\ ") - - # Append start and end markers for each file - file_content = f"# ----[FILE_START]{file_path}[FILE_CONTENT]:\n" + \ - file_content + \ - f"\n# ----[FILE_END]{file_path}\n" - - # Merge the file contents - merged_file += file_content - - # Update the progress bar description - tqdm_desc = f"Reading file: {file_path}" - progress.set_description(tqdm_desc) - - # Return the merged file as a Symbol - return self._to_symbol(merged_file) \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/symai/extended/graph.py b/symbolicai-main/symbolicai-main/symai/extended/graph.py deleted file mode 100644 index a5da3de321f8699c69882f41f8ae9a2951a48553..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/extended/graph.py +++ /dev/null @@ -1,85 +0,0 @@ -from multiprocessing import Pool -from typing import Callable - -from .. import core -from ..formatter import SentenceFormatter -from ..post_processors import StripPostProcessor -from ..pre_processors import PreProcessor -from ..prompts import Prompt -from ..symbol import Expression, Symbol - -GRAPH_DESCRIPTION = """[Description] -Build source-target relationship pairs for named entities based for the [DATA] section. The [DATA] section contains one sentence. -Format all extracted pairs in a CSV format with the following columns: source, target, count. -The source is related to the target based on intermediate terms, such as "has a", "has two", "is used to" etc. -If more than one entity pair is extracted from the same sentence, then the CSV file should contain multiple rows separated by a newline (\\n) -""" - - -class GraphPreProcessor(PreProcessor): - def __call__(self, argument): - return '$> {} =>'.format(str(argument.args[0])) - - -class Graph(Expression): - @property - def static_context(self) -> str: - return GRAPH_DESCRIPTION - - def __init__(self, formatter: Callable = SentenceFormatter(), n_workers: int = 1, verbose: bool = False, **kwargs): - super().__init__(**kwargs) - self.formatter = formatter - self.n_workers = n_workers - self.sym_return_type = Graph - self.verbose = verbose - - def process_symbol(self, s, *args, **kwargs): - res = '' - - @core.few_shot(prompt="Extract relationships between entities:\n", - examples=Prompt([ - '$> John has a dog. =>John, dog, 1 EOF', - '$> Karl has two sons. =>Karl, sons, 2 EOF', - '$> Similarly, the term general linguistics is used to distinguish core linguistics from other types of study =>general linguistics, core linguistics, 1 EOF', - '$> X has Y and Z has Y =>X, Y, 1\nZ, Y, 1 EOF', - ]), - pre_processors=[GraphPreProcessor()], - post_processors=[StripPostProcessor()], - stop=['EOF'], **kwargs) - def _func(_, text) -> str: - pass - - if len(str(s)) > 0: - if self.verbose: print(s) - r = _func(self, s) - rec = str(r) - lines = rec.split('\n') - for l in lines: - l = l.strip() - if len(l) > 0: - csv = l.split(',') - try: - if len(csv) == 3 and \ - csv[0].strip() != '' and \ - csv[1].strip() != '' and \ - int(csv[2].strip()) > 0: - res += l + '\n' - except Exception as e: - if self.verbose: print(e) - pass - return res - - def forward(self, sym: Symbol, **kwargs) -> Symbol: - res = 'source,target,value\n' - sym_list = self.formatter(sym).value - if self.n_workers == 1: - for s in sym_list: - res += self.process_symbol(s) - return res - with Pool(self.n_workers) as p: - results = p.map(self.process_symbol, sym_list) - for r in results: - res += r - return res - - diff --git a/symbolicai-main/symbolicai-main/symai/extended/html_style_template.py b/symbolicai-main/symbolicai-main/symai/extended/html_style_template.py deleted file mode 100644 index c1a877160cb8219973fde0c9721894cc3393b6a7..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/extended/html_style_template.py +++ /dev/null @@ -1,88 +0,0 @@ -from ..components import Stream, Style, Template -from ..symbol import Expression, Symbol - -HEADER_STYLE_DESCRIPTION = """[Description] -Design a web view of data with HTML. -Use dark theme and best practices for colors, text font, etc. -Use Bootstrap for styling. - -[Examples] -Chose the appropriate HTML tags: -- Use URL links such as http://www.example.com to: -- Use tag for images: http://www.../image.jpeg -- Use

    ...

    tags for the titles and headers:

    ...

    tags for paragraphs -- Use
      ...
    tags for unordered lists ['demo', 'example', ...]:
    • demo
    • example
    • ...
    - -[Template] - - - - - - Generated HTML Results - - - -
    -

    Rendered results:

    - - {{placeholder}} -
    - -""" - -HTML_STREAM_STYLE_DESCRIPTION = """[Description]: -Style the elements according to the bootstrap library. -Add animations if appropriate. -DO NOT change the content values, only add styling. -DO NOT add \n \n \n ' list 'chrome: url' =>['chrome://resources/css/text_defaults_md.css', 'chrome://theme/colors.css?sets=ui,chrome']""", - ]) - - -class ExpandFunction(Prompt): - def __init__(self): - super().__init__([ - """$> Ping if google is still available => -def _llm_ping_(): - "Ping if google is still available." - import os - response = os.system("ping -c 1 google.com") - return response == 0 """ + Prompt.stop_token, - - """$> Create a random number between 1 and 100 => -def _llm_random_(): - "Create a random number between 1 and 100." - import random - return random.randint(1, 100) """ + Prompt.stop_token, - - """$> Write any sentence in capital letters => -def _llm_upper_(input_): - "Write any sentence in capital letters." - return input_.upper() """ + Prompt.stop_token, - - """$> Open a file from the file system => -def _llm_open_(file_name): - "Open a file form the file system." - return open(file_name, "r") """ + Prompt.stop_token, - - """$> Call OpenAI GPT-3 to perform an action given a user input => -def _llm_action_(input_): - "Call OpenAI GPT-3 to perform an action given a user input." - import openai - openai.Completion.create(prompt=input_, model="text-davinci-003") """ + Prompt.stop_token, - - """$> Create a prompt to translate a user query to an answer in well-formatted structure => -def _llm_action_(query_, answer_): - "Create a prompt to translate a user query to an answer in well-formatted structure." - return f"Query: {query_} => {answer_}" """ + Prompt.stop_token, - ]) - - -class ForEach(Prompt): - def __init__(self): - super().__init__([ - "[1, 2, 3, 4, 5, 12, 48, 89, 99, 1, 4, 1] foreach '1' apply '+1' =>[2, 3, 4, 5, 6, 13, 49, 90, 100, 2, 5, 2]", - "'I have four cats at home. Kitty, Mitsi, Pauli and Corni.' foreach 'cat' apply 'upper' =>I have four CATS at home. KITTY, MITSI, PAULI and CORNI.", - "'Yesterday I went to four supermarkets. Best Buy, Super Target, Costco and Big Target.' foreach '{supermarket}' apply '*{supermarket}*' =>Yesterday I went to four supermarkets. *Best Buy*, *Super Target*, *Costco* and *Big Target*.", - "'Yesterday I went to the supermarket. I bought a lot of food. Here is my shopping list: papaya, apples, bananas, oranges, ham, fish, mangoes, grapes, passion fruit, kiwi, strawberries, eggs, cucumber, and many more.' foreach 'fruit' apply 'pluralize' =>Yesterday I went to the supermarket. I bought a lot of food. Here is my shopping list: papayas, apples, bananas, oranges, ham, fish, mangoes, grapes, passion fruits, kiwis, strawberries, eggs, cucumber, and many more.", - "'Ananas' foreach 'letter a' apply 'upper' =>AnAnAs", - "['New York', 'Madrid', 'Tokyo'] foreach 'city' apply 'list continent' =>['North America', 'Europe', 'Asia']", - "'Ananas' foreach 'letter' apply 'list' =>['A', 'n', 'a', 'n', 'a', 's']", - "'Hello World, Hola Mundo, Buenos Dias, Bonjour' foreach 'greeting' apply 'translate to English' =>Hello World, Hello World, Good Morning, Good Day", - "['house', 'boat', 'mobile phone', 'iPhone', 'computer', 'soap', 'board game'] foreach 'electronic device' apply 'add price $100' =>['house', 'boat', 'mobile phone $100', 'iPhone $100', 'computer $100', 'soap', 'board game']", - "'1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10' foreach 'even number' apply '-1' =>1 | 1 | 3 | 3 | 5 | 5 | 7 | 7 | 9 | 9", - """'\n \n \n ' foreach 'chrome: url' apply 'replace chrome:// with https://google.' =>\n \n \n """, - ]) - - -class MapContent(Prompt): - def __init__(self): - super().__init__([ - "[1, 2, 3, 4, 5, 12, 48, 89, 99, 1, 4, 1] map 'number parity' =>{'even numbers': [2, 4, 12, 48, 4], 'odd numbers': [1, 3, 5, 89, 99, 1]}", - "'Kitty, Mitsi, Pauli and Corni. We also have two dogs: Pluto and Bello' map 'animal names' =>{'cats': ['Kitty', 'Mitsi', 'Pauli', 'Corni'], 'dogs': ['Pluto', 'Bello'], 'description': ['I have four cats at home.', 'We also have two dogs:']}" - "'Yesterday I went to the supermarket. I bought a lot of food. Here is my shopping list: papaya, apples, bananas, oranges, ham, fish, mangoes, grapes, passion fruit, kiwi, strawberries, eggs, cucumber, and many more.' map 'fruits and other shopping items' =>{'fruits': ['papaya', 'apples', 'bananas', 'oranges', 'mangoes', 'grapes', 'passion fruit', 'kiwi', 'strawberries'], 'other items': ['ham', 'fish', 'eggs', 'cucumber', 'and many more'], 'description': ['Yesterday I went to the supermarket.', 'I bought a lot of food.', 'Here is my shopping list:']}", - "'Ananas' map 'letters to counts' =>{'letters': {'A': 1, 'n': 2, 'a': 2, 's': 1}", - "['New York', 'Madrid', 'Tokyo'] map 'cities to continents' =>{'New York': 'North America', 'Madrid': 'Europe', 'Tokyo': 'Asia'}", - "['cars where first invented in the 1800s', 'ducks are birds', 'dinosaurs are related to birds', 'Gulls, or colloquially seagulls, are seabirds of the family Laridae', 'General Motors is the largest car manufacturer in the world'] map 'sentences to common topics' =>{'birds': ['ducks are birds', 'dinosaurs are related to birds', 'Gulls, or colloquially seagulls, are seabirds of the family Laridae'], 'cars': ['cars where first invented in the 1800s', 'General Motors is the largest car manufacturer in the world']}", - ]) - - -class Index(Prompt): - def __init__(self): - super().__init__([ - "[1, 2, 3, 4, 5, 12, 48, 89, 99, 1, 4, 1] index 1 =>2", - "[1, 2, 3, 4, 5, 12, 48, 89, 99, 1, 4, 1] index 'first item' =>1", - "'I have four cats at home. Kitty, Mitsi, Pauli and Corni.' index 'first cat name' =>Kitty", - "'I have four cats at home. Kitty, Mitsi, Pauli and Corni.' index '0' =>I", - "'I have four cats at home. Kitty, Mitsi, Pauli and Corni.' index 1 =>have", - "'I have four cats at home. Kitty, Mitsi, Pauli and Corni.' index 2 =>four", - "'Yesterday I went to the supermarket. I bought a lot of food.' index 'food name' =>None", - "'Yesterday I went to the supermarket.' index 'pronoun' =>I", - "'Yesterday I went to the supermarket.' index 'time' =>Yesterday", - "'Yesterday I went to the supermarket.' index 'verb' =>went", - "'Yesterday I went to the supermarket. I bought a lot of food. Here is my shopping list: papaya, apples, bananas, oranges, ham, fish, mangoes, grapes, passion fruit, kiwi, strawberries, eggs, cucumber, and many more.' index 'last fruit' =>strawberries", - "'Ananas' index '5' =>s", - "'Hello World, Hola Mundo, Buenos Dias, Bonjour' index 'second to last greeting' =>Buenos Dias", - "'Hello World, Hola Mundo, Buenos Dias, Bonjour' index 'second greeting' =>Hola Mundo", - "['house', 'boat', 'mobile phone', 'iPhone', 'computer', 'soap', 'board game'] index 'electronic devices' =>['mobile phone', 'iPhone', 'computer']", - "1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 index '2:5' =>[3, 4, 5]", - """'\n \n \n ' index 'href urls' =>['chrome://resources/css/text_defaults_md.css', 'chrome://theme/colors.css?sets=ui,chrome']""", - ]) - - -class SetIndex(Prompt): - def __init__(self): - super().__init__([ - "[1, 2, 3, 4, 5, 12, 48, 89, 99, 1, 4, 1] index 1 set '7' =>[1, 7, 3, 4, 5, 12, 48, 89, 99, 1, 4, 1]", - "[1, 2, 3, 4, 5, 12, 48, 89, 99, 1, 4, 1] index 'first item' set 8 =>[8, 2, 3, 4, 5, 12, 48, 89, 99, 1, 4, 1]", - "'I have four cats at home. Kitty, Mitsi, Pauli and Corni.' index 'first cat name' set 'Mittens' =>'I have four cats at home. Mittens, Mitsi, Pauli and Corni.'", - "'I have four cats at home. Kitty, Mitsi, Pauli and Corni.' index '0' set 'you' =>You have four cats at home. Kitty, Mitsi, Pauli and Corni.'", - "'I have four cats at home. Kitty, Mitsi, Pauli and Corni.' index 1 set 'negate' =>I don't have four cats at home. Kitty, Mitsi, Pauli and Corni.'", - "'I have four cats at home. Kitty, Mitsi, Pauli and Corni.' index 2 set 'add one' =>I have five cats at home. Kitty, Mitsi, Pauli and Corni.'", - "'Yesterday I went to the supermarket. I bought a lot of food.' index 'food name' set 'bread' =>Yesterday I went to the supermarket. I bought a lot of bread.", - "'Yesterday I went to the supermarket. I bought a lot of food. Here is my shopping list: papaya, apples, bananas, oranges, ham, fish, mangoes, grapes, passion fruit, kiwi, strawberries, eggs, cucumber, and many more.' index 'fruits' set 'appliences: ['oven', 'fridge', 'dishwasher', 'washing machine']' =>Yesterday I went to the supermarket. I bought a lot of suppliences. Here is my shopping list: oven, fridge, dishwasher, washing machine, and many more.", - "'Ananas' index '5' set 'upper case' =>AnanAs", - "'Why am I so stupid?' index 'stupid' set 'smart' =>Why am I so smart?", - "'What is this lazy dog doing here?' index 'lazy' set 'cute' =>What is this cute dog doing here?", - "'Hello World, Hola Mundo, Buenos Dias, Bonjour' index 'second to last greeting' set 'German' =>Hello World, Hola Mundo, Guten Tag, Bonjour", - "'Hello World, Hola Mundo, Buenos Dias, Bonjour' index 'second greeting' set 'lower case' =>Hello World, hola mundo, Buenos Dias, Bonjour", - "['house', 'boat', 'mobile phone', 'iPhone', 'computer', 'soap', 'board game'] index 'electronic devices' set 'empty' =>['house', 'boat', 'soap', 'board game']", - "1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 index '2:5' set '0' =>[1, 0, 0, 0, 5, 6, 7, 8, 9, 10]", - """'\n \n \n ' index 'href urls' set 'http://www.google.com' =>'\n \n \n '""", - ]) - - -class RemoveIndex(Prompt): - def __init__(self): - super().__init__([ - "[1, 2, 3, 4, 5, 12, 48, 89, 99, 1, 4, 1] remove 1 =>[1, 3, 4, 5, 12, 48, 89, 99, 1, 4, 1]", - "[1, 2, 3, 4, 5, 12, 48, 89, 99, 1, 4, 1] remove 'first item' =>[2, 3, 4, 5, 12, 48, 89, 99, 1, 4, 1]", - "'I have four cats at home. Kitty, Mitsi, Pauli and Corni.' remove 'first cat name' =>I have four cats at home. Mitsi, Pauli and Corni.'", - "'I have four cats at home. Kitty, Mitsi, Pauli and Corni.' remove '0' =>There are four cats at home. Kitty, Mitsi, Pauli and Corni.'", - "'I have four cats at home. Kitty, Mitsi, Pauli and Corni.' remove 2 =>I have four cats at home. Kitty, Pauli and Corni.'", - "'Yesterday I went to the supermarket. I bought a lot of food.' remove 'food' =>Yesterday I went to the supermarket. I bought a lot.", - "'Yesterday I went to the supermarket. I bought a lot of food. Here is my shopping list: papaya, apples, bananas, oranges, ham, fish, mangoes, grapes, passion fruit, kiwi, strawberries, eggs, cucumber, and many more.' remove 'fruits' =>Yesterday I went to the supermarket. I bought a lot of food. Here is my shopping list: ham, fish, and many more.", - "'Ananas' remove 'upper case' =>nanas", - "'Ananas' remove 0 =>nanas", - "'Hello World, Hola Mundo, Buenos Dias, Bonjour' remove 'Spanish' =>Hello World, Bonjour", - "'Hello World, Hola Mundo, Buenos Dias, Bonjour' remove 'second greeting' =>Hello World, Buenos Dias, Bonjour", - "['house', 'boat', 'mobile phone', 'iPhone', 'computer', 'soap', 'board game'] remove 'electronic devices' =>['house', 'boat', 'soap', 'board game']", - "1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 remove '2:5' =>[1, 2, 6, 7, 8, 9, 10]", - """'\n \n \n ' remove 'hrefs' =>\n \n \n """, - ]) - - -class SimulateCode(Prompt): - def __init__(self): - super().__init__([ -"""code '# Import the SymPy library -from sympy import * -# Define the symbolic variables that will be used -x, y, z = symbols('x y z') -# Define the expression to be manipulated -expr = (x + y) ** 2 -# Use SymPy's simplify() function to simplify the expression -simplified_expr = simplify(expr) -# Print the simplified expression -print(simplified_expr)' params 'x = 2, y = 3' =>x^2 + 2*x*y + y^2 | 2^2 + 2*2*3 + 3^2 | 4 + 12 + 9 | 25""", -"""code '# Import the built-in os and sys modules -import os -import sys -# Open the file for reading -with open(file_name, 'r') as file: - # Read the file contents - contents = file.read() - # Print the file contents - print(contents)' params 'test_file.txt' =>Hello world!""", - """code 'numbers = [1, 2, 3, 4, 5] - total = 0 - for num in numbers: - total += num - print(f"Sum is: {total}")' params '' =>Step 1: Initialize empty list [1, 2, 3, 4, 5] and total = 0 | Step 2: First iteration, num = 1, total = 0 + 1 = 1 | Step 3: Second iteration, num = 2, total = 1 + 2 = 3 | Step 4: Third iteration, num = 3, total = 3 + 3 = 6 | Step 5: Fourth iteration, num = 4, total = 6 + 4 = 10 | Step 6: Fifth iteration, num = 5, total = 10 + 5 = 15 | Step 7: Print "Sum is: 15""", - - """code 'age = 25 - if age >= 18: - status = "adult" - can_vote = True - else: - status = "minor" - can_vote = False - print(f"Person is {status}, voting: {can_vote}")' params '' =>Step 1: Set age = 25 | Step 2: Check condition age >= 18, which is 25 >= 18, this is True | Step 3: Since condition is True, execute if branch | Step 4: Set status = "adult" | Step 5: Set can_vote = True | Step 6: Skip else branch | Step 7: Print "Person is adult, voting: True""", - - """code 'def factorial(n): - if n <= 1: - return 1 - else: - return n * factorial(n-1) - result = factorial(4)' params '' =>PSEUDOCODE SIMULATION: - FUNCTION factorial(n): - IF n <= 1 THEN RETURN 1 - ELSE RETURN n * factorial(n-1) - END FUNCTION - - EXECUTION TRACE: - Call factorial(4) | Check 4 <= 1? False, so return 4 * factorial(3) | Call factorial(3) | Check 3 <= 1? False, so return 3 * factorial(2) | Call factorial(2) | Check 2 <= 1? False, so return 2 * factorial(1) | Call factorial(1) | Check 1 <= 1? True, so return 1 | Unwinding: factorial(2) = 2 * 1 = 2 | factorial(3) = 3 * 2 = 6 | factorial(4) = 4 * 6 = 24 | Result = 24""", - - """code 'data = {"name": "Alice", "scores": [85, 92, 78]} - average = sum(data["scores"]) / len(data["scores"]) - data["average"] = round(average, 1) - print(f"{data['name']}'s average: {data['average']}")' params '' =>Step 1: Create dictionary with name="Alice" and scores list [85, 92, 78] | Step 2: Calculate sum of scores: 85 + 92 + 78 = 255 | Step 3: Get length of scores list: 3 | Step 4: Calculate average: 255 / 3 = 85.0 | Step 5: Round average to 1 decimal place: 85.0 | Step 6: Add average to dictionary: data["average"] = 85.0 | Step 7: Print "Alice's average: 85.0""" -]) - - -class GenerateCode(Prompt): - def __init__(self): - super().__init__([ -"""description 'Generate an efficient Python function to compute the Fibonacci sequence of numbers.' =>def fibonacci(n): - # Initialize a list with the first two numbers in the sequence - fib = [0, 1] - # If n is less than or equal to 1, return the first n numbers in the sequence - if n <= 1: - return fib[:n] - # Otherwise, compute the remaining numbers in the sequence - for i in range(2, n): - fib.append(fib[i-1] + fib[i-2]) - # Return the entire sequence of numbers - return fib""", - """description 'Generate a Java function to compute the number pi.' =>public static double computePi() { - double pi = 0; - int sign = 1; - for (int i = 0; i < 1000000; i++) { - pi += sign * (1.0 / (2 * i + 1)); - sign *= -1; - } - pi *= 4; - return pi; - }""", - """description 'Generate a C++ file with a function to compute the Fast Fourier transform.' =>#include -#include -using namespace std; -constexpr int N = 16; // number of elements in the input array -constexpr double PI = 3.14159265358979323846; -// Compute the FFT of the given input array, storing the result in the given output array. -void fft(complex* input, complex* output) { - for (int i = 0; i < N; ++i) { - output[i] = 0; - for (int j = 0; j < N; ++j) { - double angle = 2 * PI * i * j / N; - output[i] += input[j] * exp(complex(0, -angle)); - } - } -}"""]) - - -class TextToOutline(Prompt): - def __init__(self): - super().__init__([ -"""text 'We introduce NPM, the first NonParametric Masked Language Model. -NPM consists of an encoder and a reference corpus, and models a nonparametric distribution over a reference corpus (Figure 1). -The key idea is to map all the phrases in the corpus into a dense vector space using the encoder and, when given a query with a [MASK] at inference, -use the encoder to locate the nearest phrase from the corpus and fill in the [MASK].' =>- first NonParametric Masked Language Model (NPM)\n - consists of encoder and reference corpus\n - key idea: map all phrases in corpus into dense vector space using encoder when given query with [MASK] at inference\n - encoder locates nearest phrase from corpus and fill in [MASK]""", -"""text 'On Monday, there will be no Phd seminar.' =>- Monday no Phd seminar""", -"""text 'The Jan. 6 select committee is reportedly planning to vote on at least three criminal referrals targeting former President Trump on Monday, a significant step from the panel as it nears the end of its year-plus investigation.' =>- Jan. 6 select committee vote criminal referrals targeting former President Trump on Monday\n-significant step end year-plus investigation""", -]) - - -class UniqueKey(Prompt): - def __init__(self): - super().__init__([ -"""text 'We introduce NPM, the first NonParametric Masked Language Model. NPM consists of an encoder and a reference corpus. =>NonParametric Masked Language Model (NPM)""", -"""text 'On Monday, there will be no Phd seminar.' =>Phd seminar""", -"""text 'The Jan. 6 select committee is reportedly planning to vote on at least three criminal referrals targeting former President Trump on Monday, a significant step from the panel as it nears the end of its year-plus investigation.' =>Jan. 6 President Trump""", -]) - - -class GenerateText(Prompt): - def __init__(self): - super().__init__([ -"""outline '- first NonParametric Masked Language Model (NPM)\n - consists of encoder and reference corpus\n - key idea: map all phrases in corpus into dense vector space using encoder when given query with [MASK] at inference\n - encoder locates nearest phrase from corpus and fill in [MASK]' =>NPM is the first NonParametric Masked Language Model. -NPM consists of an encoder and a reference corpus, and models a nonparametric distribution over a reference corpus (Figure 1). -The key idea is to map all the phrases in the corpus into a dense vector space using the encoder and, when given a query with a [MASK] at inference, -use the encoder to locate the nearest phrase from the corpus and fill in the [MASK].""", -"""outline '- Monday no Phd seminar' =>On Monday, there will be no Phd seminar.""", -"""outline '- Jan. 6 select committee vote criminal referrals targeting former President Trump on Monday\n-significant step end year-plus investigation' =>The Jan. 6 select committee is reportedly planning to vote on at least three criminal referrals targeting former President Trump on Monday, a significant step from the panel as it nears the end of its year-plus investigation.""" -]) - - -class SymbiaCapabilities(Prompt): - def __init__(self): - super().__init__([ -''' -Experience: - * [WORLD-KNOWLEDGE]: Employ your world knowledge to answer questions on various subjects seen during the training phase. - * [RECALL]: Use your [RECALL] functionality when prompted to remember or retrieve information from your memory. - * [DK]: Utilize the [DK] category for cases when you do not understand the user's intent or when the query is ambiguous or invalid. - * [EXIT]: Use the [EXIT] category to identify and understand the user's intent to close or end the session (e.g., when the user says goodbye, leave, exit, quit, etc.). - * [HELP]: Use the [HELP] category when the user requests information about your capabilities and tools. List the available tools and categories in a user-friendly manner. - -Toolbox: - * [SEARCH]: Utilize the [SEARCH] tool to find relevant data from multiple sources across the internet. - * [SYMBOLIC]: Use the [SYMBOLIC] tool to perform complex computations, generate plots, and provide solutions to mathematical problems. - * [CRAWLER]: Employ the [CRAWLER] tool to crawl websites and extract specific information as mandated by the task. - * [SPEECH-TO-TEXT]: Use the [SPEECH-TO-TEXT] tool to convert audio files or voice input into text data. - * [TEXT-TO-IMAGE]: Utilize the [TEXT-TO-IMAGE] engine to create image content based on textual descriptions provided by the task. - * [OCR]: Deploy the [OCR] tool to extract text data from image files, scanned documents, or other sources with embedded text. - * [RETRIEVAL]: Use the [RETRIEVAL] tool to extract specific pieces of information from text documents. - -Instructions: - - Perform context classification by understanding the query's intention and then decide whether to use internal knowledge, a tool, or to address ambiguity or confusion. - - Return the anwser in the format: [#category](#reflection), where #category is one of the categories above and #reflection is the explanation for why you classified the query as a first-person narrative. - - Do NOT provide any additional information beyond the category and explanation! - -Examples: - Query: "What is the weather in New York?" - Answer: [SEARCH](The query falls under the search category since it requires up-to-date weather information which goes beyond my internal knowledge.) - - Query: "What is the derivative of x^2?" - Answer: [SYMBOLIC](The query pertains to the realm of math and necessitates a symbolic engine response. Given my tendency to hallucinate, I may lack the ability to accurately answer this question independently.) - - Query: "Kjwe ewqjc qwjren. knowledge?" - Answer: [DK](The query is not a valid English sentence and I am unable to understand it. I should inform the user that I don't understand the query and ask them to rephrase it.) - - Query: "What is the meaning of life?" - Answer: [WORLD-KNOWLEDGE](The query is asks a deep philosophical question, which is a topic I have a lot of knowledge about because I was trained on many philosophical texts.) - - Query: "Who is the president of the United States?" - Answer: [SEARCH](The query is a search query because it asks about a topic I might not be aware of because it might have changed since I was trained.) - - Query: "Tea or coffee?" - Answer: [DK](The query is ambiguous. I should ask the user to clarify it.) - - Query: "How is the distress in Syria?" - Answer: [SEARCH](The query is a search query because it asks about a political topic I might not be aware of because it might have changed since I was trained. I must notice the fact that the question doesn't ask about a particular historical event, which would have been a question that I could tackle based on my own internal knowledge.) - - Query: "How do I solve a quadratic equation?" - Answer: [WORLD-KNOWLEDGE](Although the query relates to mathematics, it lacks sufficient data for employing a symbolic engine. My internal knowledge is more suitable for this task.) - - Query: "What is $P(A) &= \sum_(i=1)^n P(A \land B_i)$?" - Answer: [WORLD-KNOWLEDGE](The query presents a mathematical equation for the probability of an event A, which I can explain. P(A) represents the probability of event A occurring, and the equation shows that it can be computed as the sum of the probabilities of A occurring along with each of the B_i events (A and B_i) for a series of n such events. This expression is based on the concept of marginal probability and is derived from the law of total probability.) - - Query: "Solve $\[\iint_R |\text(J)|\mathrm(d)r\mathrm(d)\theta = \int_(0)^(2\pi)\int_(0)^(R) \begin(vmatrix)\dfrac(\partial x)(\partial r) & \dfrac(\partial x)(\partial \theta) \\ \dfrac(\partial y)(\partial r) & \dfrac(\partial y)(\partial \theta)\end(vmatrix) \, \mathrm(d)r\mathrm(d)\theta\]$." - Answer: [SYMBOLIC](The query asks to solve a double integral involving the Jacobian determinant, which requires a symbolic engine like WolframAlpha to correctly compute the answer.) - - Query: "Can you extract the names of all contributors from this GitHub repository: https://github.com/example/repository?" - Answer: [CRAWLER](This query requires me to crawl a specific website, provided by the link, and extract the names of all contributors from the GitHub repository. The task is best suited for the crawler tool.) - - Query: "Generate a meme with a dog sitting at a table and the caption 'This is fine.'" - Answer: [TEXT-TO-IMAGE](The query requests the creation of a meme based on a textual description. To achieve this, the optimal approach is using the text-to-image engine.) - - Query: "Create an image of a sunset over the ocean." - Answer: [TEXT-TO-IMAGE](The query requests the creation of an image based on a textual description. To achieve this, the optimal approach is using the text-to-image engine.) - - Query: "Convert this audio recording of a lecture to text: File: C:\\Users\\Username\\Documents\\Audio\\lec10.wav" - Answer: [SPEECH-TO-TEXT](The query asks to transcribe an audio file containing a lecture with a provided file path. The most appropriate solution is to use the speech-to-text tool to convert the audio content into text data.) - - Query: "What does this scanned document say? The document is located here: /home/username/Documents/bills.png" - Answer: [OCR](The query asks to extract text information from a scanned document with a provided local file path. The optical character recognition tool is designed for this task, making it the appropriate choice.) - - Query: "What is the most important advice from the book 'The 7 Habits of Highly Effective People'? File path: C:\\Users\\Username\\Documents\\7_Habits_book.pdf" - Answer: [RETRIEVAL](This query asks me to retrieve a specific piece of information from a document (in this case, a book in PDF format), with a provided local file path. The appropriate solution is to use the retrieval tool to locate, open, and extract the requested fact from the text.) - - Query: "What was the major finding in the experiment from the report? Here's the path to the file: ~/xmachine/Documents/report.pdf" - Answer: [RETRIEVAL](This query asks me to extract the major finding of an experiment from a report provided as a local file in a Unix-based file system. The appropriate solution is to use the retrieval tool to open, analyze, and extract the relevant information from the document.) - - Query: "I want an Italian pizza recipe, but I don't want to use any meat. Can you find one for me?" - Answer: [SEARCH](While I do possess knowledge about various recipes, finding a specific Italian pizza recipe without meat is best achieved using the SEARCH tool. It allows me to browse through a wider range of sources and provide a more tailored solution to your request.) - - Query: "Can you briefly describe the French Revolution?" - Answer: [WORLD-KNOWLEDGE](Given my extensive training on various subjects, including history, I can provide a brief overview of the French Revolution based on my world knowledge. This approach is suitable as the query seeks a general understanding rather than specific or up-to-date details.) - - Query: "I'm done for now. Thank you." - Answer: [EXIT](The user is expressing that they have finished their current interaction and is expressing gratitude. It's appropriate to exit and close the session.) - - Query: "Quit!" - Answer: [EXIT](The user has given a direct command to "Quit!" which demonstrates their intent to end the session. Recognizing this, it's time to terminate the session as requested.) - - Query: "What are your capabilities?" - Answer: [HELP](My capabilities include answering questions relying on my internal training, handling unclear or ambiguous questions, utilizing search tools to find information on the internet, performing complex mathematical tasks, gathering specific information from websites, transcribing audio files, creating images based on text descriptions, extracting text from images or scanned documents, and retrieving facts from text documents.) - - Query: "How can you help me?" - Answer: [HELP](I can assist you in different tasks relying on my available capabilities. Whether you need help with answering questions, mathematical calculations, finding information online, transcribing audio, or extracting information from documents, I can provide support.) - - Query: "I'm thinking about my kids again..." - Answer: [RECALL](I need to reflect on my past interactions with the user to determine if they mentioned this information to me.) - - Query: "Please remember that my favorite color is blue." - Answer: [RECALL](The user wants me to keep their favorite color in my memory. I will remember that blue is their favorite color and be ready to use this information in future conversations.) - - Query: "Who won the tennis game between John and Alice that I watched last week?" - Answer: [RECALL](To answer this question, I must access the memory of the information provided earlier about a tennis game between John and Alice that the user watched last week.) -''' -]) - - -class MemoryCapabilities(Prompt): - def __init__(self): - super().__init__([ -''' -Categories: -* [SAVE]: Save the information in the agent's long-term memory because it is relevant and useful for future interactions with the user. -* [DUPLICATE]: The information is already present in the agent's long-term memory, and there is no need to save it again. -* [IRRELEVANT]: The information is not worth saving in the agent's long-term memory because it is unrelated or of no importance to the tasks or user's needs. - -Instructions: -- Analyze the information provided in the scratchpad, user query, and agent's reflection of the query to determine the appropriate category for the given context. -- Frame your response in the format: [#category](#reflection), where #category is one of the categories ([SAVE], [DUPLICATE], or [IRRELEVANT]) and #reflection is the rationale behind your classification choice. -- Consider the long-term memory recalls to identify if the information is already present or could be a duplicate. -- In your reflection, refer to the user in the third person (using "the user" or "they" instead of "you"). - -Scratchpad format: -[REFLECT]( - Query: The last user query. - Reflection: The agent's reflection of the user query. -) - -[SHORT-TERM MEMORY RECALL]( - The agent retrieved the following memories from their short-term memory. -) - -[LONG-TERM MEMORY RECALL]( - The agent retrieved the following memories from their long-term memory. -) - -Examples: -[CONTEXT]( - Query: My dog's name is Bella. - Reflection: The user is sharing the name of their dog, which is Bella. -) - -[SHORT-TERM MEMORY RECALL]( - User: Do you have any pets? - Agent: As an AI, I do not have pets, but I can help you with any pet-related questions or concerns. -) - -[LONG-TERM MEMORY RECALL]( - User: My dog, Bella, likes to play fetch. -) - -Answer: [DUPLICATE](The user has already mentioned their dog's name, Bella, in a previous conversation. Since this information is already stored in the long-term memory, it is not necessary to save it again.) - -[CONTEXT]( - Query: How's the weather today? - Reflection: The user is asking about the weather today. -) - -[SHORT-TERM MEMORY RECALL]( - User: What's the temperature like today? - Agent: Today's temperature is expected to be around 75 degrees Fahrenheit with clear skies. -) - -[LONG-TERM MEMORY RECALL]( -No memories retrieved. -) - -Answer: [IRRELEVANT](The user's query is about a transient information like today's weather, which is not useful for future interactions. There is no need to save this information in the long-term memory.) - -[CONTEXT]( - Query: I graduated from Harvard University. - Reflection: The user is sharing that they graduated from Harvard University. -) - -[SHORT-TERM MEMORY RECALL]( - User: Can you help me with college-related questions? - Agent: Absolutely! I can assist you with general information, application processes, or any specific questions related to colleges. -) - -[LONG-TERM MEMORY RECALL]( - No memories retrieved. -) - -Answer: [SAVE](The user has provided relevant information about their educational background by mentioning that they graduated from Harvard University. This information could be important for future conversations and assistance related to higher education topics, so it should be stored in the long-term memory.) -''' -]) - - -ProbabilisticBooleanModeStrict = "true" -ProbabilisticBooleanModeMedium = "'true', 'yes', 'ok', ['true']" -ProbabilisticBooleanModeTolerant = "'true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'ok', ['true']" diff --git a/symbolicai-main/symbolicai-main/symai/server/__init__.py b/symbolicai-main/symbolicai-main/symai/server/__init__.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/server/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/symbolicai-main/symbolicai-main/symai/server/huggingface_server.py b/symbolicai-main/symbolicai-main/symai/server/huggingface_server.py deleted file mode 100644 index b2d584d9cd701069530887a746848c91262f5c7e..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/server/huggingface_server.py +++ /dev/null @@ -1,194 +0,0 @@ -import argparse -import random -from typing import List, Optional - -import numpy as np -import torch -from fastapi import FastAPI, Request -from pydantic import BaseModel -from transformers import (AutoModelForCausalLM, AutoTokenizer, - BitsAndBytesConfig, StoppingCriteria, - StoppingCriteriaList) - -# General arguments -parser = argparse.ArgumentParser(description="FastAPI server for Hugging Face models") -parser.add_argument("--model", type=str, help="Path to the model") -parser.add_argument("--host", type=str, default="localhost", help="Host address. (default: localhost)") -parser.add_argument("--port", type=int, default=8000, help="Port number. (default: 8000)") - -# Quantization arguments with 'quant_' prefix -parser.add_argument("--quant", action="store_true", default=False, help="Enable quantization; see help for available quantization options (default: False)") -parser.add_argument("--quant_load_in_8bit", action="store_true", default=False, help="Load model in 8-bit precision (default: False)") -parser.add_argument("--quant_load_in_4bit", action="store_true", default=False, help="Load model in 4-bit precision (default: False)") -parser.add_argument("--quant_llm_int8_threshold", type=float, default=6.0, help="LLM int8 threshold (default: 6.0)") -parser.add_argument("--quant_llm_int8_skip_modules", type=str, nargs="+", default=None, help="LLM int8 skip modules (default: None)") -parser.add_argument("--quant_llm_int8_enable_fp32_cpu_offload", action="store_true", default=False, help="Enable FP32 CPU offload for LLM int8 (default: False)") -parser.add_argument("--quant_llm_int8_has_fp16_weight", action="store_true", default=False, help="LLM int8 has FP16 weight (default: False)") -parser.add_argument("--quant_bnb_4bit_compute_dtype", type=str, default=None, help="BNB 4-bit compute dtype (default: None)") -parser.add_argument("--quant_bnb_4bit_quant_type", type=str, default="fp4", help="BNB 4-bit quantization type (default: fp4)") -parser.add_argument("--quant_bnb_4bit_use_double_quant", action="store_true", default=False, help="Use double quantization for BNB 4-bit (default: False)") -parser.add_argument("--quant_bnb_4bit_quant_storage", type=str, default=None, help="BNB 4-bit quantization storage (default: None)") - -# Model inference arguments -# https://huggingface.co/docs/transformers/main/en/main_classes/model -parser.add_argument("--torch_dtype", type=str, default="auto", help="A string that is a valid torch.dtype. E.g. “float32” loads the model in torch.float32, “float16” loads in torch.float16 etc. (default: auto)") -parser.add_argument("--attn_implementation", type=str, default="sdpa", help='The attention implementation to use in the model (if relevant). Can be any of "eager" (manual implementation of the attention), "sdpa" (using F.scaled_dot_product_attention), or "flash_attention_2" (using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. (default: sdpa)') -parser.add_argument("--device_map", type=str, default="auto", help="A string that is a valid device. E.g. “cuda” loads the model on the GPU, “cpu” loads it on the CPU. (default: auto)") - -args = parser.parse_args() - -quant_config = BitsAndBytesConfig( - load_in_8bit=args.quant_load_in_8bit, - load_in_4bit=args.quant_load_in_4bit, - llm_int8_threshold=args.quant_llm_int8_threshold, - llm_int8_skip_modules=args.quant_llm_int8_skip_modules, - llm_int8_enable_fp32_cpu_offload=args.quant_llm_int8_enable_fp32_cpu_offload, - llm_int8_has_fp16_weight=args.quant_llm_int8_has_fp16_weight, - bnb_4bit_compute_dtype=args.quant_bnb_4bit_compute_dtype, - bnb_4bit_quant_type=args.quant_bnb_4bit_quant_type, - bnb_4bit_use_double_quant=args.quant_bnb_4bit_use_double_quant, - bnb_4bit_quant_storage=args.quant_bnb_4bit_quant_storage -) - -app = FastAPI() - -tokenizer = AutoTokenizer.from_pretrained(args.model) - -if args.quant: - model = AutoModelForCausalLM.from_pretrained( - args.model, - device_map=args.device_map, - torch_dtype=args.torch_dtype, - attn_implementation=args.attn_implementation, - quantization_config=quant_config, - ) -else: - model = AutoModelForCausalLM.from_pretrained( - args.model, - device_map=args.device_map, - torch_dtype=args.torch_dtype, - attn_implementation=args.attn_implementation, - ) - -def set_seed(seed): - random.seed(seed) - np.random.seed(seed) - torch.manual_seed(seed) - if torch.cuda.is_available(): - torch.cuda.manual_seed_all(seed) - -class StoppingCriteriaSub(StoppingCriteria): - # https://discuss.huggingface.co/t/implimentation-of-stopping-criteria-list/20040/13 - def __init__(self, stop_words, tokenizer): - super().__init__() - self.stop_words = stop_words - self.tokenizer = tokenizer - - def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: - for stop_word in self.stop_words: - if self.tokenizer.decode(input_ids[0][-len(self.tokenizer.encode(stop_word)):]).strip() == stop_word: - return True - return False - -class TokenizeRequest(BaseModel): - input: str - add_special_tokens: Optional[bool] = False - -class DetokenizeRequest(BaseModel): - tokens: List[int] - skip_special_tokens: Optional[bool] = True - -class ChatCompletionRequest(BaseModel): - messages: List[dict] - temperature: float = 1. - top_p: float = 1. - stop: Optional[List[str]] = None - seed: Optional[int] = None - max_tokens: Optional[int] = 2048 - max_tokens_forcing: Optional[int] = None - top_k: int = 50 - logprobs: bool = False - do_sample: bool = True - num_beams: int = 1 - num_beam_groups: int = 1 - eos_token_id: Optional[int] = None - -@app.post("/chat") -def chat_completions(request: ChatCompletionRequest): - chat = request.messages - #@TODO: is there a way to assert that the loaded model has chat capabilities? - inputs = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True) - inputs = tokenizer(inputs, return_tensors="pt").to(model.device) - - generation_config = { - "max_length": request.max_tokens, - "max_new_tokens": request.max_tokens_forcing, - "temperature": request.temperature, - "top_p": request.top_p, - "top_k": request.top_k, - "do_sample": request.do_sample, - "num_beams": request.num_beams, - "num_beam_groups": request.num_beam_groups, - "eos_token_id": request.eos_token_id if request.eos_token_id is not None else tokenizer.eos_token_id, - "output_logits": request.logprobs, - "return_dict_in_generate": True, - } - - if request.stop: - generation_config["stopping_criteria"] = StoppingCriteriaList([StoppingCriteriaSub(stop_words=request.stop, tokenizer=tokenizer)]) - - if request.seed: - set_seed(request.seed) - - outputs = model.generate(**inputs, **generation_config) - - new_tokens = outputs.sequences[0][inputs.input_ids.shape[-1]:] - generated_text = tokenizer.decode(new_tokens, skip_special_tokens=True) - - response = { - "choices": [ - { - "message": { - "role": "assistant", - "content": generated_text - } - }, - ], - "metadata": { - "model": args.model, - "model_name": model.config.name_or_path, - "model_class": model.__class__.__name__, - "model_device": model.device.type, - "model_vocab_size": model.config.vocab_size, - "model_output_scores": request.logprobs, - "model_do_sample": request.do_sample, - "model_temperature": request.temperature, - "model_top_p": request.top_p, - "model_top_k": request.top_k, - "model_max_tokens": request.max_tokens, - "model_seed": request.seed, - "model_stopping_criteria": request.stop, - "model_eos_token_id": request.eos_token_id, - "logits": [logits.tolist() for logits in outputs.logits], - "model_input": chat, - "model_chat_format": tokenizer.chat_template, - } - } - - return response - -@app.post("/tokenize") -def tokenize(request: TokenizeRequest): - tokens = tokenizer.encode(request.input, add_special_tokens=request.add_special_tokens) - return {"tokens": tokens} - -@app.post("/detokenize") -def detokenize(request: DetokenizeRequest): - text = tokenizer.decode(request.tokens, skip_special_tokens=request.skip_special_tokens) - return {"text": text} - -def huggingface_server(): - import uvicorn - from functools import partial - command = partial(uvicorn.run, app) - return command, args diff --git a/symbolicai-main/symbolicai-main/symai/server/llama_cpp_server.py b/symbolicai-main/symbolicai-main/symai/server/llama_cpp_server.py deleted file mode 100644 index ac3625f83e95373dc599b7e613a6bf6d61543ea8..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/server/llama_cpp_server.py +++ /dev/null @@ -1,51 +0,0 @@ -import argparse -import subprocess -import sys -import os -from loguru import logger - -def llama_cpp_server(): - parser = argparse.ArgumentParser(description="A wrapper for llama_cpp.", add_help=False) - parser.add_argument("--help", action="store_true", help="Show available options for llama_cpp server.") - parser.add_argument("--env", choices=['python', 'cpp'], default='python', - help="Choose programming environment (python or cpp)") - parser.add_argument("--cpp-server-path", type=str, help="Path to llama.cpp server executable") - - main_args, llama_cpp_args = parser.parse_known_args() - - if main_args.help: - if main_args.env == 'python': - command = [sys.executable, "-m", "llama_cpp.server", "--help"] - subprocess.run(command) - else: - if not main_args.cpp_server_path: - logger.error("Error: --cpp-server-path is required when using cpp environment") - sys.exit(1) - if not os.path.exists(main_args.cpp_server_path): - logger.error(f"Error: Executable not found at {main_args.cpp_server_path}") - sys.exit(1) - command = [main_args.cpp_server_path, "--help"] - subprocess.run(command) - sys.exit(0) - - if main_args.env == 'cpp': - if not main_args.cpp_server_path: - logger.error("Error: --cpp-server-path is required when using cpp environment") - sys.exit(1) - if not os.path.exists(main_args.cpp_server_path): - logger.error(f"Error: Executable not found at {main_args.cpp_server_path}") - sys.exit(1) - command = [ - main_args.cpp_server_path, - *llama_cpp_args, - ] - llama_cpp_args = [arg for arg in llama_cpp_args if not arg.startswith("--embedding")] # Exclude embedding argument - else: # python - command = [ - sys.executable, - "-m", - "llama_cpp.server", - *llama_cpp_args, - ] - - return command, llama_cpp_args diff --git a/symbolicai-main/symbolicai-main/symai/shell.py b/symbolicai-main/symbolicai-main/symai/shell.py deleted file mode 100644 index 69f66cf5d48caeb199563aaae2c875e702f0554d..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/shell.py +++ /dev/null @@ -1,139 +0,0 @@ -import argparse -import os - -from .components import Lambda, Try -from .core import few_shot -from .misc.console import ConsoleStyle -from .misc.loader import Loader -from .post_processors import StripPostProcessor -from .pre_processors import PreProcessor -from .symbol import Expression -from .shellsv import run as shellsv_run -from . import SYMAI_VERSION - - -SHELL_CONTEXT = """[Description] -This shell program is the command interpreter on the Linux systems, MacOS and Windows PowerShell. -It is a program that interacts with the users in the terminal emulation window. -Shell commands are instructions that instruct the system to do some action. - -[Program Instructions] -You will only process user queries and return valid Linux/MacOS shell or Windows PowerShell commands and no other text. -EOF is the end of file character and marks the end of the output command. -If you do not understand the user query, then return an sorry message and ask the user to rephrase the query. -If no further specified, use as default the Linux/MacOS shell commands. -Additional instructions are provided in examples or via dynamic context in the prompt. - -[Examples] -Some of the commonly used shell commands are: -// List the contents of the current directory in long format. -$> ls -l EOF -// This command concatenates and prints the contents of the file. If there is no file, then it reads the standard input -$> cat file EOF -// This command is used to create a new directory called helloworld. -$> mkdir helloworld EOF -// command to copy the /path/to/file1 to /second/path/to/other/file2. -$> cp /path/to/file1 /second/path/to/other/file2 EOF -// Linux env variable OPENAI_API_KEY with value "". -$> export OPENAI_API_KEY= EOF -// Set Windows env variable OPENAI_API_KEY with value "". -$> $Env:OPENAI_API_KEY="" EOF -// Create a Directory in PowerShell -$> New-Item -ItemType Directory -Path EOF - -[Last Example] --------------- -""" - -class ShellPreProcessor(PreProcessor): - def __call__(self, argument): - return '// {}\n$>'.format(str(argument.prop.instance)) - - -class Shell(Expression): - def forward(self, **kwargs) -> str: - @few_shot(prompt="Convert a user query to a shell command:\n", - examples=[], - pre_processors=[ShellPreProcessor()], - post_processors=[StripPostProcessor()], - stop=['EOF'], **kwargs) - def _func(_) -> str: - return "Sorry, something went wrong. Please check if your backend is available and try again or report an issue to the devs. :(" - - return Shell(_func(self)) - - @property - def static_context(self) -> str: - return SHELL_CONTEXT - - -def process_query(args) -> None: - if args.version: - with ConsoleStyle('extensity') as console: - console.print(f"ExtensityAI: Symbolic Shell v{SYMAI_VERSION}") - return - - query = args.query - if query is None or len(query) == 0: - with ConsoleStyle('extensity') as console: - console.print(f"Starting ExtensityAI: Symbolic Shell v{SYMAI_VERSION}") - shellsv_run(auto_query_on_error=args.auto, - conversation_style=args.style if args.style is not None and args.style != '' else None, - verbose=args.verbose) - return - - shell = Shell(query) - - with Loader(desc="Inference ...", end=""): - msg = shell() - - if args.edit: - msg = msg.modify(args.edit) - if args.convert: - msg = msg.convert(args.convert) - if args.add: - msg = msg << args.add - if args.delete: - msg = msg - args.delete - if args.exec: - msg = str(msg).strip().replace('EOF', '') - os.system(msg) - if args.more: - cmd = msg.extract('the main command used') - cmd_help = cmd << 'get manual for the command' - expr = Try(expr=Lambda(lambda kwargs: os.system(str(kwargs['args'][0])))) - with Loader(desc="Inference ...", end=""): - expr(cmd_help) - - with ConsoleStyle('code') as console: - msg = str(msg).strip().replace('EOF', '') - console.print(msg) - - -def run() -> None: - # All the logic of argparse goes in this function - parser = argparse.ArgumentParser(description='Welcome to the Symbolic Shell support tool!') - parser.add_argument('query', type=str, nargs='?', help='The prompt for the shell query.') - parser.add_argument('--add', dest='add', default="", required=False, type=str, - help='integrate the added text to the query.') - parser.add_argument('--convert', dest='convert', default="", required=False, type=str, - help='convert a command to another shell. (e.g. --convert=windows or --convert=linux)') - parser.add_argument('--edit', dest='edit', default="", required=False, type=str, - help='edit the added text to the query.') - parser.add_argument('--del', dest='delete', default="", required=False, type=str, - help='remove the added text to the query.') - parser.add_argument('--more', dest='more', default=False, required=False, action=argparse.BooleanOptionalAction, - help='add more context to the generated command.') - parser.add_argument('--exec', dest='exec', default=False, required=False, action=argparse.BooleanOptionalAction, - help='execute command after creation (ATTENTION: Executing a generated command without verification may be risky!).') - parser.add_argument('--auto', dest='auto', default=False, required=False, action=argparse.BooleanOptionalAction, - help='query the the LLM if a command resulted unsuccessfully.') - parser.add_argument('--style', dest='style', default=None, required=False, type=str, - help='add speech style to the shell.') - parser.add_argument('--version', dest='version', default=False, required=False, action=argparse.BooleanOptionalAction, - help='show the version of the shell.') - parser.add_argument('--verbose', action='store_true', - help='Print verbose errors.') - - args = parser.parse_args() - process_query(args) diff --git a/symbolicai-main/symbolicai-main/symai/shellsv.py b/symbolicai-main/symbolicai-main/symai/shellsv.py deleted file mode 100644 index 8d14dc095b927f3b0c48b42f8128412d2fb1fd42..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/shellsv.py +++ /dev/null @@ -1,893 +0,0 @@ -import argparse -import glob -import json -import logging -import os -import re -import shutil -import signal -import subprocess -import sys -import time -import traceback -from pathlib import Path -from typing import Iterable, Tuple - -from prompt_toolkit import HTML, PromptSession, print_formatted_text -from prompt_toolkit.completion import Completer, Completion, WordCompleter -from prompt_toolkit.history import History -from prompt_toolkit.key_binding import KeyBindings -from prompt_toolkit.keys import Keys -from prompt_toolkit.lexers import PygmentsLexer -from prompt_toolkit.patch_stdout import patch_stdout -from prompt_toolkit.shortcuts import CompleteStyle, ProgressBar -from prompt_toolkit.styles import Style -from pygments.lexers.shell import BashLexer - -from .backend.settings import HOME_PATH, SYMSH_CONFIG -from .components import FileReader, Function, Indexer -from .extended import (ArxivPdfParser, Conversation, DocumentRetriever, - FileMerger, RepositoryCloner, - RetrievalAugmentedConversation) -from .imports import Import -from .interfaces import Interface -from .menu.screen import show_intro_menu -from .misc.console import ConsoleStyle -from .misc.loader import Loader -from .symbol import Symbol - -logging.getLogger("prompt_toolkit").setLevel(logging.ERROR) -logging.getLogger("asyncio").setLevel(logging.ERROR) -logging.getLogger("subprocess").setLevel(logging.ERROR) - -# load json config from home directory root -home_path = HOME_PATH -config_path = os.path.join(home_path, 'symsh.config.json') -# migrate config from old path -if 'colors' not in SYMSH_CONFIG: - __new_config__ = {"colors": SYMSH_CONFIG} - # add command in config - SYMSH_CONFIG = __new_config__ - # save config - with open(config_path, 'w') as f: - json.dump(__new_config__, f, indent=4) - -# make sure map-nt-cmd is in config -if 'map-nt-cmd' not in SYMSH_CONFIG: - # add command in config - SYMSH_CONFIG['map-nt-cmd'] = True - # save config - with open(config_path, 'w') as f: - json.dump(SYMSH_CONFIG, f, indent=4) - -print = print_formatted_text -FunctionType = Function -ConversationType = Conversation -RetrievalConversationType = RetrievalAugmentedConversation -use_styles = False -map_nt_cmd_enabled = SYMSH_CONFIG['map-nt-cmd'] - -SHELL_CONTEXT = """[Description] -This shell program is the command interpreter on the Linux systems, MacOS and Windows PowerShell. -It is a program that interacts with the users in the terminal emulation window. -Shell commands are instructions that instruct the system to do some action. - -[Program Instructions] -If the user requests commands, you will only process user queries and return valid Linux/MacOS shell or Windows PowerShell commands and no other text. -If no further specified, use as default the Linux/MacOS shell commands. -If additional instructions are provided the follow the user query to produce the requested output. -A well related and helpful answer with suggested improvements is preferred over "I don't know" or "I don't understand" answers or stating the obvious. -""" - -stateful_conversation = None -previous_kwargs = None - -def supports_ansi_escape(): - try: - os.get_terminal_size(0) - return True - except OSError: - return False - -class PathCompleter(Completer): - def get_completions(self, document, complete_event): - complete_word = document.get_word_before_cursor(WORD=True) - sep = os.path.sep - if complete_word.startswith(f'~{sep}'): - complete_word = FileReader.expand_user_path(complete_word) - - # list all files and directories in current directory - files = list(glob.glob(complete_word + '*')) - if len(files) == 0: - return None - - dirs_ = [] - files_ = [] - - for file in files: - # split the command into words by space (ignore escaped spaces) - command_words = document.text.split(' ') - if len(command_words) > 1: - # Calculate start position of the completion - start_position = len(document.text) - len(' '.join(command_words[:-1])) - 1 - start_position = max(0, start_position) - else: - start_position = len(document.text) - # if there is a space in the file name, then escape it - if ' ' in file: - file = file.replace(' ', '\\ ') - if (document.text.startswith('cd') or document.text.startswith('mkdir')) and os.path.isfile(file): - continue - if os.path.isdir(file): - dirs_.append(file) - else: - files_.append(file) - - for d in dirs_: - # if starts with home directory, then replace it with ~ - d = FileReader.expand_user_path(d) - yield Completion(d, start_position=-start_position, - style='class:path-completion', - selected_style='class:path-completion-selected') - - for f in files_: - # if starts with home directory, then replace it with ~ - f = FileReader.expand_user_path(f) - yield Completion(f, start_position=-start_position, - style='class:file-completion', - selected_style='class:file-completion-selected') - -class HistoryCompleter(WordCompleter): - def get_completions(self, document, complete_event): - completions = super().get_completions(document, complete_event) - for completion in completions: - completion.style = 'class:history-completion' - completion.selected_style = 'class:history-completion-selected' - yield completion - -class MergedCompleter(Completer): - def __init__(self, path_completer, history_completer): - self.path_completer = path_completer - self.history_completer = history_completer - - def get_completions(self, document, complete_event): - text = document.text - - if text.startswith('cd ') or\ - text.startswith('ls ') or\ - text.startswith('touch ') or\ - text.startswith('cat ') or\ - text.startswith('mkdir ') or\ - text.startswith('open ') or\ - text.startswith('rm ') or\ - text.startswith('git ') or\ - text.startswith('vi ') or\ - text.startswith('nano ') or\ - text.startswith('*') or\ - text.startswith(r'.\\') or\ - text.startswith(r'~\\') or\ - text.startswith(r'\\') or\ - text.startswith('.\\') or\ - text.startswith('~\\') or\ - text.startswith('\\') or\ - text.startswith('./') or\ - text.startswith('~/') or\ - text.startswith('/'): - yield from self.path_completer.get_completions(document, complete_event) - yield from self.history_completer.get_completions(document, complete_event) - else: - yield from self.history_completer.get_completions(document, complete_event) - yield from self.path_completer.get_completions(document, complete_event) - -# Create custom keybindings -bindings = KeyBindings() -previous_prefix = None -exec_prefix = 'default' -# Get a copy of the current environment -default_env = os.environ.copy() - -def get_exec_prefix(): - return sys.exec_prefix if exec_prefix == 'default' else exec_prefix - -def get_conda_env(): - # what conda env am I in (e.g., where is my Python process from)? - ENVBIN = get_exec_prefix() - env_name = os.path.basename(ENVBIN) - return env_name - -# bind to 'Ctrl' + 'Space' -@bindings.add(Keys.ControlSpace) -def _(event): - current_user_input = event.current_buffer.document.text - func = FunctionType(SHELL_CONTEXT) - - bottom_toolbar = HTML(' [f] Print "f" [x] Abort.') - - # Create custom key bindings first. - kb = KeyBindings() - - cancel = [False] - @kb.add('f') - def _(event): - print('You pressed `f`.') - - @kb.add('x') - def _(event): - " Send Abort (control-c) signal. " - cancel[0] = True - os.kill(os.getpid(), signal.SIGINT) - - # Use `patch_stdout`, to make sure that prints go above the - # application. - with patch_stdout(): - with ProgressBar(key_bindings=kb, bottom_toolbar=bottom_toolbar) as pb: - # TODO: hack to simulate progress bar of indeterminate length of an synchronous function - for i in pb(range(100)): - if i > 50 and i < 70: - time.sleep(.01) - - if i == 60: - res = func(current_user_input) # hack to see progress bar - - # Stop when the cancel flag has been set. - if cancel[0]: - break - - with ConsoleStyle('code') as console: - console.print(res) - -@bindings.add(Keys.PageUp) -def _(event): - # Moving up for 5 lines - for _ in range(5): - event.current_buffer.auto_up() - -@bindings.add(Keys.PageDown) -def _(event): - # Moving down for 5 lines - for _ in range(5): - event.current_buffer.auto_down() - -class FileHistory(History): - ''' - :class:`.History` class that stores all strings in a file. - ''' - - def __init__(self, filename: str) -> None: - self.filename = filename - super().__init__() - - def load_history_strings(self) -> Iterable[str]: - lines: list[str] = [] - - if os.path.exists(self.filename): - with open(self.filename, "r") as f: - lines = f.readlines() - # Remove comments and empty lines. - lines = [line for line in lines if line.strip() and not line.startswith("#")] - # Remove whitespace at the end and \n. - lines = [line.rstrip() for line in lines] - # only keep unique lines - lines = list(dict.fromkeys(lines)) - - # Reverse the order, because newest items have to go first. - return reversed(lines) - - def store_string(self, string: str) -> None: - # Save to file. - with open(self.filename, "ab") as f: - - def write(t: str) -> None: - f.write(t.encode("utf-8")) - - for line in string.split("\n"): - write("%s\n" % line) - -# Defining commands history -def load_history(home_path=HOME_PATH, history_file='.bash_history'): - history_file_path = os.path.join(home_path, history_file) - history = FileHistory(history_file_path) - return history, list(history.load_history_strings()) - -# Function to check if current directory is a git directory -def get_git_branch(): - try: - git_process = subprocess.Popen(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) - stdout, stderr = git_process.communicate() - if git_process.returncode == 0: - return stdout.strip().decode('utf-8') - except FileNotFoundError: - pass - return None - -def disambiguate(cmds: str) -> Tuple[str, int]: - ''' - Ok, so, possible options for now: - 1. query | cmd - 2. query | file [file ...] - -- not supported - 3. query | cmd | file - 4. query | cmd cmd ... - 5. query | file | cmd - ''' - has_at_least_one_cmd = any([shutil.which(cmd) is not None for cmd in cmds.split(' ')]) - maybe_cmd = cmds.split(' ')[0].strip() # get first command - maybe_files = FileReader.extract_files(cmds) - # if cmd follows file(s) or file(s) follows cmd throw error as not supported - if maybe_files is not None and has_at_least_one_cmd: - raise ValueError('Cannot disambiguate commands that have both files and commands or multiple commands. Please provide correct order of commands. ' - 'Supported are: ' - 'query | file [file ...] (e.g. "what do these files have in common?" | file1 [file2 ...]) ' - 'and ' - 'query | cmd (e.g. "what flags can I use with rg?" | rg --help)') - # now check order of commands and keep correct order - if shutil.which(maybe_cmd) is not None: - cmd_out = subprocess.run(cmds, capture_output=True, text=True, shell=True) - if not cmd_out.stdout: - raise ValueError(f'Command not found or failed. Error: {cmd_out.stderr}') - return cmd_out.stdout, 1 - if maybe_files is not None: - return maybe_files, 2 - -# query language model -def query_language_model(query: str, res=None, *args, **kwargs): - global stateful_conversation, previous_kwargs - home_path = HOME_PATH - symai_path = os.path.join(home_path, '.conversation_state') - plugin = SYMSH_CONFIG.get('plugin_prefix') - - # check and extract kwargs from query if any - # format --kwargs key1=value1,key2=value2,key3=value3,...keyN=valueN - if '--kwargs' in query or '-kw' in query: - splitter = '--kwargs' if '--kwargs' in query else '-kw' - # check if kwargs format is last in query otherwise raise error - splits = query.split(f'{splitter}') - if previous_kwargs is None and '=' not in splits[-1] and ',' not in splits[-1]: - raise ValueError('Kwargs format must be last in query.') - elif previous_kwargs is not None and '=' not in splits[-1] and ',' not in splits[-1]: - # use previous kwargs - cmd_kwargs = previous_kwargs - else: - # remove kwargs from query - query = splits[0].strip() - # extract kwargs - kwargs_str = splits[-1].strip() - cmd_kwargs = dict([kw.split('=') for kw in kwargs_str.split(',')]) - cmd_kwargs = {k.strip(): Symbol(v.strip()).ast() for k, v in cmd_kwargs.items()} - - previous_kwargs = cmd_kwargs - # unpack cmd_kwargs to kwargs - kwargs = {**kwargs, **cmd_kwargs} - - # Handle stateful conversations: - # 1. If query starts with !" (new conversation), create new conversation state - # 2. If query starts with ." (follow-up), either: - # - Load existing conversation state if it exists - # - Create new conversation state if none exists - if (query.startswith('!"') or query.startswith("!'") or query.startswith('!`')): - os.makedirs(os.path.dirname(symai_path), exist_ok=True) - stateful_conversation = ConversationType(auto_print=False) - ConversationType.save_conversation_state(stateful_conversation, symai_path) - # Special case: if query starts with !" and has a prefix, run the prefix command and store the output - if plugin is not None: - with Loader(desc="Inference ...", end=""): - cmd = query[1:].strip('\'"') - cmd = f"symrun {plugin} '{cmd}' --disable-pbar" - cmd_out = run_shell_command(cmd, auto_query_on_error=True) - stateful_conversation.store(cmd_out) - ConversationType.save_conversation_state(stateful_conversation, symai_path) - return cmd_out - elif query.startswith('."') or query.startswith(".'") or query.startswith('.`'): - try: - stateful_conversation = stateful_conversation.load_conversation_state(symai_path) - except Exception: - with ConsoleStyle('error') as console: - console.print('No conversation state found. Please start a new conversation.') - return - if plugin is not None: - with Loader(desc="Inference ...", end=""): - query = query[1:].strip('\'"') - answer = stateful_conversation(query).value - cmd = f"symrun {plugin} '{answer}' --disable-pbar" - cmd_out = run_shell_command(cmd, auto_query_on_error=True) - stateful_conversation.store(cmd_out) - ConversationType.save_conversation_state(stateful_conversation, symai_path) - return cmd_out - cmd = None - if '|' in query: - cmds = query.split('|') - if len(cmds) > 2: - raise ValueError(('Cannot disambiguate commands that have more than 1 pipes. Please provide correct order of commands. ' - 'Supported are: ' - 'query | file [file ...] (e.g. "what do these files have in common?" | file1 [file2 ...]) ' - 'and ' - 'query | cmd (e.g. "what flags can I use with rg?" | rg --help)')) - query = cmds[0] - payload, order = disambiguate(cmds[1].strip()) - # check if we're in a stateful conversation - is_stateful = query.startswith(('.', '!')) and any(query.startswith(f"{prefix}{quote}") - for prefix in ['.', '!'] - for quote in ['"', "'", '`']) - - if is_stateful: - func = stateful_conversation - else: - func = FunctionType(payload) if order == 1 else ConversationType(file_link=payload, auto_print=False) - - if is_stateful: - if order == 1: - func.store(payload) - elif order == 2: - for file in payload: - func.store_file(file) - else: - if query.startswith('."') or query.startswith(".'") or query.startswith('.`') or\ - query.startswith('!"') or query.startswith("!'") or query.startswith('!`'): - func = stateful_conversation - else: - func = FunctionType(SHELL_CONTEXT) - - with Loader(desc="Inference ...", end=""): - if res is not None: - query = f"[Context]\n{res}\n\n[Query]\n{query}" - msg = func(query, *args, **kwargs) - - if stateful_conversation is not None and ( - query.startswith('."') or query.startswith(".'") or query.startswith('.`') or - query.startswith('!"') or query.startswith("!'") or query.startswith('!`') - ): - ConversationType.save_conversation_state(stateful_conversation, symai_path) - - return msg - -def retrieval_augmented_indexing(query: str, index_name = None, *args, **kwargs): - global stateful_conversation - sep = os.path.sep - path = query - - # check if path contains overwrite flag - overwrite = False - if path.startswith('!'): - overwrite = True - path = path[1:] - - # check if request use of specific index - use_index_name = False - if path.startswith('index:'): - use_index_name = True - # continue conversation with specific index - index_name = path.split('index:')[-1].strip() - else: - parse_arxiv = False - - # check if path contains arxiv flag - if path.startswith('arxiv:'): - parse_arxiv = True - - # check if path contains git flag - if path.startswith('git@'): - overwrite = True - repo_path = os.path.join(home_path, 'temp') - cloner = RepositoryCloner(repo_path=repo_path) - url = path[4:] - if 'http' not in url: - url = 'https://' + url - url = url.replace('.com:', '.com/') - # if ends with '.git' then remove it - if url.endswith('.git'): - url = url[:-4] - path = cloner(url) - - # merge files - merger = FileMerger() - file = merger(path) - # check if file contains arxiv pdf file and parse it - if parse_arxiv: - arxiv = ArxivPdfParser() - pdf_file = arxiv(file) - if pdf_file is not None: - file = file |'\n'| pdf_file - - index_name = path.split(sep)[-1] if index_name is None else index_name - index_name = Indexer.replace_special_chars(index_name) - print(f'Indexing {index_name} ...') - - # creates index if not exists - DocumentRetriever(index_name=index_name, file=file, overwrite=overwrite) - - home_path = HOME_PATH - symai_path = os.path.join(home_path, '.conversation_state') - os.makedirs(os.path.dirname(symai_path), exist_ok=True) - stateful_conversation = RetrievalConversationType(auto_print=False, index_name=index_name) - Conversation.save_conversation_state(stateful_conversation, symai_path) - if use_index_name: - message = 'New session ' - else: - message = f'Repository {url} cloned and ' if query.startswith('git@') or query.startswith('git:') else f'Directory {path} ' - msg = f'{message}successfully indexed: {index_name}' - return msg - -def search_engine(query: str, res=None, *args, **kwargs): - search = Interface('serpapi') - with Loader(desc="Searching ...", end=""): - search_query = Symbol(query).extract('search engine optimized query') - res = search(search_query) - with Loader(desc="Inference ...", end=""): - func = FunctionType(query) - msg = func(res, payload=res) - # write a temp dump file with the query and results - home_path = HOME_PATH - symai_path = os.path.join(home_path, '.search_dump') - os.makedirs(os.path.dirname(symai_path), exist_ok=True) - with open(symai_path, 'w') as f: - f.write(f'[SEARCH_QUERY]:\n{search_query}\n[RESULTS]\n{res}\n[MESSAGE]\n{msg}') - return msg - -def set_default_module(cmd: str): - if cmd.startswith('set-plugin'): - module = cmd.split('set-plugin')[-1].strip() - SYMSH_CONFIG['plugin_prefix'] = module - with open(config_path, 'w') as f: - json.dump(SYMSH_CONFIG, f, indent=4) - msg = f"Default plugin set to '{module}'" - elif cmd == 'unset-plugin': - SYMSH_CONFIG['plugin_prefix'] = None - with open(config_path, 'w') as f: - json.dump(SYMSH_CONFIG, f, indent=4) - msg = "Default plugin unset" - elif cmd == 'get-plugin': - msg = f"Default plugin is '{SYMSH_CONFIG['plugin_prefix']}'" - - with ConsoleStyle('success') as console: - console.print(msg) - -def handle_error(cmd, res, message, auto_query_on_error): - msg = Symbol(cmd) | f'\n{str(res)}' - if 'command not found' in str(res) or 'not recognized as an internal or external command' in str(res): - return res.stderr.decode('utf-8') - else: - stderr = res.stderr - if stderr and auto_query_on_error: - rsp = stderr.decode('utf-8') - print(rsp) - msg = msg | f"\n{rsp}" - if 'usage:' in rsp: - try: - cmd = cmd.split('usage: ')[-1].split(' ')[0] - # get man page result for command - res = subprocess.run('man -P cat %s' % cmd, - shell=True, - stdout=subprocess.PIPE) - stdout = res.stdout - if stdout: - rsp = stdout.decode('utf-8')[:500] - msg = msg | f"\n{rsp}" - except Exception: - pass - - return query_language_model(msg) - else: - stdout = res.stdout - if stdout: - message = stderr.decode('utf-8') - return message - -# run shell command -def run_shell_command(cmd: str, prev=None, auto_query_on_error: bool=False, stdout=None, stderr=None): - if prev is not None: - cmd = prev + ' && ' + cmd - message = None - conda_env = get_exec_prefix() - # copy default_env - new_env = default_env.copy() - if exec_prefix != 'default': - # remove current env from PATH - new_env["PATH"] = new_env["PATH"].replace(sys.exec_prefix, conda_env) - # Execute the command - try: - stdout = subprocess.PIPE if auto_query_on_error else stdout - stderr = subprocess.PIPE if auto_query_on_error else stderr - res = subprocess.run(cmd, shell=True, stdout=stdout, stderr=stderr, env=new_env) - if res and stdout and res.stdout: - message = res.stdout.decode('utf-8') - elif res and stderr and res.stderr: - message = res.stderr.decode('utf-8') - except FileNotFoundError as e: - return e - except PermissionError as e: - return e - - # all good - if res.returncode == 0: - return message - # If command not found, then try to query language model - else: - return handle_error(cmd, res, message, auto_query_on_error) - -def is_llm_request(cmd: str): - return cmd.startswith('"') or cmd.startswith('."') or cmd.startswith('!"') or cmd.startswith('?"') or\ - cmd.startswith("'") or cmd.startswith(".'") or cmd.startswith("!'") or cmd.startswith("?'") or\ - cmd.startswith('`') or cmd.startswith('.`') or cmd.startswith('!`') or cmd.startswith('?`') or\ - cmd.startswith('!(') - -def map_nt_cmd(cmd: str, map_nt_cmd_enabled: bool = True): - if os.name.lower() == 'nt' and map_nt_cmd_enabled and not is_llm_request(cmd): - # Mapping command replacements with regex for commands with variants - cmd_mappings = { - r'\bls\b(-[a-zA-Z]*)?' : r'dir \1', # Maps 'ls' with or without arguments - r'\bmv\b\s+(.*)' : r'move \1', # Maps 'mv' with any arguments - r'\bcp\b\s+(.*)' : r'copy \1', # Maps 'cp' with any arguments - r'\btouch\b\s+(.*)' : r'type nul > \1', # Maps 'touch filename' to 'type nul > filename' - r'\brm\b\s+(-rf)?' : r'del \1', # Maps 'rm' and 'rm -rf' - r'\bdiff\b\s+(.*)' : r'fc \1', # Maps 'diff' with any arguments - r'\bgrep\b\s+(.*)' : r'find \1', # Maps 'grep' with any arguments - r'\bpwd\b' : 'chdir', # pwd has no arguments - r'\bdate\b' : 'time', # date has no arguments - r'\bmkdir\b\s+(.*)' : r'md \1', # Maps 'mkdir' with any arguments - r'\bwhich\b\s+(.*)' : r'where \1', # Maps 'which' with any arguments - r'\b(vim|nano)\b\s+(.*)' : r'notepad \2', # Maps 'vim' or 'nano' with any arguments - r'\b(mke2fs|mformat)\b\s+(.*)' : r'format \2', # Maps 'mke2fs' or 'mformat' with any arguments - r'\b(rm\s+-rf|rmdir)\b' : 'rmdir /s /q', # Matches 'rm -rf' or 'rmdir' - r'\bkill\b\s+(.*)' : r'taskkill \1', # Maps 'kill' with any arguments - r'\bps\b\s*(.*)?' : r'tasklist \1', # Maps 'ps' with any or no arguments - r'\bexport\b\s+(.*)' : r'set \1', # Maps 'export' with any arguments - r'\b(chown|chmod)\b\s+(.*)' : r'attrib +r \2', # Maps 'chown' or 'chmod' with any arguments - r'\btraceroute\b\s+(.*)' : r'tracert \1', # Maps 'traceroute' with any arguments - r'\bcron\b\s+(.*)' : r'at \1', # Maps 'cron' with any arguments - r'\bcat\b\s+(.*)' : r'type \1', # Maps 'cat' with any arguments - r'\bdu\s+-s\b' : 'chkdsk', # du -s has no arguments, chkdsk is closest in functionality - r'\bls\s+-R\b' : 'tree', # ls -R has no arguments - } - - # Remove 1:1 mappings - direct_mappings = { - 'clear': 'cls', - 'man' : 'help', - 'mem' : 'free', - } - - cmd_mappings.update(direct_mappings) - - # Iterate through mappings and replace commands - for linux_cmd, windows_cmd in cmd_mappings.items(): - # copy original command - original_cmd = cmd - cmd = re.sub(linux_cmd, windows_cmd, cmd) - if cmd != original_cmd: - print(f'symsh >> command "{original_cmd}" mapped to "{cmd}"\n') - - return cmd - -def process_command(cmd: str, res=None, auto_query_on_error: bool=False): - global exec_prefix, previous_prefix - - # map commands to windows if needed - cmd = map_nt_cmd(cmd) - if cmd.startswith('set-plugin') or cmd == 'unset-plugin' or cmd == 'get-plugin': - return set_default_module(cmd) - - sep = os.path.sep - # check for '&&' to also preserve pipes '|' in normal shell commands - if '" && ' in cmd or "' && " in cmd or '` && ' in cmd: - if is_llm_request(cmd): - # Process each command (the ones involving the LLM) separately - cmds = cmd.split(' && ') - if not is_llm_request(cmds[0]): - return ValueError('The first command must be a LLM request.') - # Process the first command as an LLM request - res = query_language_model(cmds[0], res=res) - rest = ' && '.join(cmds[1:]) - if '$1' in cmds[1]: - res = str(res).replace('\n', r'\\n') - rest = rest.replace('$1', '"%s"' % res) - res = None - cmd = rest - # If it's a normal shell command with pipes or &&, pass it whole - res = run_shell_command(cmd, prev=res, auto_query_on_error=auto_query_on_error) - return res - - if cmd.startswith('?"') or cmd.startswith("?'") or cmd.startswith('?`'): - cmd = cmd[1:] - return search_engine(cmd, res=res) - - elif is_llm_request(cmd) or '...' in cmd: - return query_language_model(cmd, res=res) - - elif cmd.startswith('*'): - cmd = cmd[1:] - return retrieval_augmented_indexing(cmd) - - elif cmd.startswith('man symsh'): - # read symsh.md file and print it - # get symsh path - pkg_path = os.path.dirname(os.path.abspath(__file__)) - symsh_path = os.path.join(pkg_path, 'symsh.md') - with open(symsh_path, 'r', encoding="utf8") as f: - return f.read() - - elif cmd.startswith('conda activate'): - # check conda execution prefix and verify if environment exists - env = sys.exec_prefix - path_ = sep.join(env.split(sep)[:-1]) - env_base = os.path.join(sep, path_) - req_env = cmd.split(' ')[2] - # check if environment exists - env_path = os.path.join(env_base, req_env) - if not os.path.exists(env_path): - return f'Environment {req_env} does not exist!' - previous_prefix = exec_prefix - exec_prefix = os.path.join(env_base, req_env) - return exec_prefix - - elif cmd.startswith('conda deactivate'): - if previous_prefix is not None: - exec_prefix = previous_prefix - if previous_prefix == 'default': - previous_prefix = None - return get_exec_prefix() - - elif cmd.startswith('conda'): - env = get_exec_prefix() - env_base = os.path.join(sep, *env.split(sep)[:-2]) - cmd = cmd.replace('conda', os.path.join(env_base, "condabin", "conda")) - return run_shell_command(cmd, prev=res, auto_query_on_error=auto_query_on_error) - - elif cmd.startswith('cd'): - try: - # replace ~ with home directory - cmd = FileReader.expand_user_path(cmd) - # Change directory - path = ' '.join(cmd.split(' ')[1:]) - if path.endswith(sep): - path = path[:-1] - return os.chdir(path) - except FileNotFoundError as e: - return e - except PermissionError as e: - return e - - elif os.path.isdir(cmd): - try: - # replace ~ with home directory - cmd = FileReader.expand_user_path(cmd) - # Change directory - os.chdir(cmd) - except FileNotFoundError as e: - return e - except PermissionError as e: - return e - - elif cmd.startswith('ll'): - - if os.name == 'nt': - cmd = cmd.replace('ll', 'dir') - return run_shell_command(cmd, prev=res) - else: - cmd = cmd.replace('ll', 'ls -la') - return run_shell_command(cmd, prev=res) - - else: - return run_shell_command(cmd, prev=res, auto_query_on_error=auto_query_on_error) - -def save_conversation(): - home_path = HOME_PATH - symai_path = os.path.join(home_path, '.conversation_state') - Conversation.save_conversation_state(stateful_conversation, symai_path) - -# Function to listen for user input and execute commands -def listen(session: PromptSession, word_comp: WordCompleter, auto_query_on_error: bool=False, verbose: bool=False): - with patch_stdout(): - while True: - try: - git_branch = get_git_branch() - conda_env = get_conda_env() - # get directory from the shell - cur_working_dir = os.getcwd() - sep = os.path.sep - if cur_working_dir.startswith(sep): - cur_working_dir = FileReader.expand_user_path(cur_working_dir) - paths = cur_working_dir.split(sep) - prev_paths = sep.join(paths[:-1]) - last_path = paths[-1] - - # Format the prompt - if len(paths) > 1: - cur_working_dir = f'{prev_paths}{sep}{last_path}' - else: - cur_working_dir = f'{last_path}' - - if git_branch: - prompt = HTML(f"{cur_working_dir} on git:[{git_branch}] conda:[{conda_env}] symsh: ❯ ") - else: - prompt = HTML(f"{cur_working_dir} conda:[{conda_env}] symsh: ❯ ") - - # Read user input - cmd = session.prompt(prompt) - if cmd.strip() == '': - continue - - if cmd == 'quit' or cmd == 'exit' or cmd == 'q': - if stateful_conversation is not None: - save_conversation() - if not use_styles: - print('Goodbye!') - else: - func = FunctionType('Give short goodbye') - print(func('bye')) - os._exit(0) - else: - msg = process_command(cmd, auto_query_on_error=auto_query_on_error) - if msg is not None: - with ConsoleStyle('code') as console: - console.print(msg) - - # Append the command to the word completer list - word_comp.words.append(cmd) - - except KeyboardInterrupt: - print() - pass - - except Exception as e: - print(e) - if verbose: - traceback.print_exc() - pass - -def create_session(history, merged_completer): - colors = SYMSH_CONFIG['colors'] - - # Load style - style = Style.from_dict(colors) - - # Session for the auto-completion - session = PromptSession(history=history, - completer=merged_completer, - complete_style=CompleteStyle.MULTI_COLUMN, - reserve_space_for_menu=5, - style=style, - key_bindings=bindings) - - return session - -def create_completer(): - # Load history - history, history_strings = load_history() - - # Create your specific completers - word_comp = HistoryCompleter(history_strings, ignore_case=True, sentence=True) - custom_completer = PathCompleter() - - # Merge completers - merged_completer = MergedCompleter(custom_completer, word_comp) - return history, word_comp, merged_completer - -def run(auto_query_on_error=False, conversation_style=None, verbose=False): - global FunctionType, ConversationType, RetrievalConversationType, use_styles - if conversation_style is not None and conversation_style != '': - print('Loading style:', conversation_style) - styles_ = Import.load_module_class(conversation_style) - FunctionType, ConversationType, RetrievalConversationType = styles_ - use_styles = True - - if SYMSH_CONFIG['show-splash-screen']: - show_intro_menu() - # set show splash screen to false - SYMSH_CONFIG['show-splash-screen'] = False - # save config - _config_path = HOME_PATH / 'symsh.config.json' - with open(_config_path, 'w') as f: - json.dump(SYMSH_CONFIG, f, indent=4) - if 'plugin_prefix' not in SYMSH_CONFIG: - SYMSH_CONFIG['plugin_prefix'] = None - - history, word_comp, merged_completer = create_completer() - session = create_session(history, merged_completer) - listen(session, word_comp, auto_query_on_error=auto_query_on_error, verbose=verbose) - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='SymSH: Symbolic Shell') - parser.add_argument('--auto-query-on-error', action='store_true', help='Automatically query the language model on error.') - parser.add_argument('--verbose', action='store_true', help='Print verbose errors.') - args = parser.parse_args() - run(auto_query_on_error=args.auto_query_on_error, conversation_style=args.conversation_style, verbose=args.verbose) diff --git a/symbolicai-main/symbolicai-main/symai/strategy.py b/symbolicai-main/symbolicai-main/symai/strategy.py deleted file mode 100644 index 1ba291e58f6a4f3a4f0dab2390e9e27c99fbbd4c..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/strategy.py +++ /dev/null @@ -1,805 +0,0 @@ -import json -import inspect -import logging -import time -from collections import defaultdict -from pydoc import locate -from typing import Callable - -import numpy as np -from beartype import beartype -from loguru import logger -from pydantic import BaseModel, ValidationError -from rich.console import Console -from rich.panel import Panel -from rich.table import Table -from rich.markup import escape - -from .components import Function -from .core_ext import deprecated -from .models import (ExceptionWithUsage, LengthConstraint, LLMDataModel, - TypeValidationError) -from .symbol import Expression - -NUM_REMEDY_RETRIES = 10 - - -class ValidationFunction(Function): - """ - Base class for validation functions that share common logic for: - • Retry attempts - • Remedy function - • Prepare seeds - • Pause/backoff logic - • Error simplification - """ - - _default_retry_params = dict( - tries=5, - delay=0.5, - max_delay=15, - backoff=2, - jitter=0.1, - graceful=False - ) - - def __init__( - self, - retry_params: dict[str, int | float | bool] = None, - verbose: bool = False, - *args, - **kwargs, - ): - super().__init__(*args, **kwargs) - if retry_params is None: - retry_params = self._default_retry_params - self.retry_params = retry_params - self.console = Console() - - # Standard remedy function for JSON correction: - self.remedy_function = Function( - "Fix the provided JSON string to ensure it is valid according to the schema and resolves all listed validation errors.", - static_context=""" - - You are tasked with fixing a string that is intended to be in **JSON format** but contains errors. - Your goal is to correct the errors and ensure the JSON string is valid according to a given JSON schema. - - - It is is very important to follow these guidelines and requirements: - - 1. Parse the provided string and use the list of validation errors to identify what needs to be fixed. - 2. Correct the identified errors to produce a properly formatted JSON string. - 3. Ensure the corrected JSON complies fully with the provided JSON schema. - 4. Preserve all original keys and values as much as possible. Only modify keys or values if they do not comply with the schema. - 5. Only modify the structure or values if necessary to meet the schema's requirements. - 6. Return the corrected JSON string as the output. - - - - - The output must be a valid, well-formatted JSON string. - - Do not introduce new data or alter the intent of the original content unless required for schema compliance. - - Ensure all changes are minimal and strictly necessary to fix the listed errors. - - """, - response_format={"type": "json_object"}, - ) - - if not verbose: - logger.disable(__name__) - else: - logger.enable(__name__) - - def prepare_seeds(self, num_seeds: int, **kwargs): - # Get list of seeds for remedy (to avoid same remedy for same input) - if "seed" in kwargs: - seed = kwargs["seed"] - elif hasattr(self, "seed"): - seed = self.seed - else: - seed = 42 - - rnd = np.random.RandomState(seed=seed) - seeds = rnd.randint( - 0, np.iinfo(np.int16).max, size=num_seeds, dtype=np.int16 - ).tolist() - return seeds - - def simplify_validation_errors(self, error: ValidationError) -> str: - """ - Simplifies Pydantic validation errors into a concise, LLM-friendly format, including lists and nested elements. - - Args: - error (ValidationError): The Pydantic ValidationError instance. - - Returns: - str: A simplified and actionable error message. - """ - simplified_errors = [] - for err in error.errors(): - field_path = " -> ".join([str(element) for element in err["loc"]]) - message = err["msg"] - expected_type = err.get("type", "unknown") - provided_value = err.get("ctx", {}).get("given", "unknown") - - error_message = ( - f"Field '{field_path}': {message}. " - f"Expected type: {expected_type}. Provided value: {provided_value}." - ) - simplified_errors.append(error_message) - - return "\n".join(simplified_errors) - - def _pause(self): - """ - Pause logic with backoff and jitter. - """ - _delay = self.retry_params['delay'] - _delay *= self.retry_params['backoff'] - - if isinstance(self.retry_params['jitter'], tuple): - _delay += np.random.uniform(*self.retry_params['jitter']) - else: - _delay += self.retry_params['jitter'] - - if self.retry_params['max_delay'] >= 0: - _delay = min(_delay, self.retry_params['max_delay']) - - def remedy_prompt(self, *args, **kwargs): - """ - Abstract or base remedy prompt method. - Child classes typically override this to include additional context needed for correction. - """ - raise NotImplementedError("Each child class needs its own remedy_prompt implementation.") - - def display_panel(self, content, title, border_style="cyan", style="#f0eee6", padding=(1,2)): - """ - Display content in a rich panel with consistent formatting. - - Args: - content: The content to display in the panel - title: The title of the panel - border_style: Color of the panel border (default: "cyan") - style: Style of the panel content (default: "#f0eee6") - padding: Padding for the panel (default: (1,2)) - """ - body = escape(content) - panel = Panel.fit(body, title=title, padding=padding, border_style=border_style, style=style) - self.console.print(panel) - - def forward(self, *args, **kwargs): - return super().forward(*args, **kwargs) # Just propagate to Function - - -class TypeValidationFunction(ValidationFunction): - """ - Performs type validation on an output, ensuring it conforms to a specified - Pydantic data model. It can also optionally perform semantic validation - if a user provides a callable designed to semantically validate the - structure of the type-validated data. - """ - def __init__( - self, - retry_params: dict[str, int | float | bool] = ValidationFunction._default_retry_params, - accumulate_errors: bool = False, - verbose: bool = False, - *args, - **kwargs, - ): - super().__init__(retry_params=retry_params, verbose=verbose, *args, **kwargs) - self.input_data_model = None - self.output_data_model = None - self.accumulate_errors = accumulate_errors - self.verbose = verbose - - def register_expected_data_model(self, data_model: LLMDataModel, attach_to: str, override: bool = False): - assert attach_to in ["input", "output"], f"Invalid attach_to value: {attach_to}; must be either 'input' or 'output'" - if attach_to == "input": - if self.input_data_model is not None and not override: - raise ValueError("There is already a data model attached to the input. If you want to override it, set `override=True`.") - self.input_data_model = data_model - elif attach_to == "output": - if self.output_data_model is not None and not override: - raise ValueError("There is already a data model attached to the output. If you want to override it, set `override=True`.") - self.output_data_model = data_model - - def remedy_prompt(self, prompt: str, output: str, errors: str) -> str: - """Override of base remedy_prompt providing instructions for fixing semantic validation errors.""" - return f""" -You are an expert in semantic validation. Your goal is to validate the output data model based on the prompt, the errors, and the output that produced the errors, and if given, the input data model and the input. - -Your prompt was: - -{prompt} - - -The input data model is: - -{self.input_data_model.simplify_json_schema() if self.input_data_model is not None else 'N/A'} - - -The given input was: - -{str(self.input_data_model) if self.input_data_model is not None else 'N/A'} - - -The output data model is: - -{self.output_data_model.instruct_llm()} - - -You've lastly generated the following output: - -{output} - - -During the semantic validation, the output was found to have the following errors: - -{errors} - - -You need to: -1. Correct the provided output to address **all listed validation errors**. -2. Ensure the corrected output adheres strictly to the requirements of the **original prompt**. -3. Preserve the intended meaning and structure of the original prompt wherever possible. - -Important guidelines: - -- The result of the task must be the output data model. -- Focus only on fixing the listed validation errors without introducing new errors or unnecessary changes. -- Ensure the revised output is clear, accurate, and fully compliant with the original prompt. -- Maintain proper formatting and any required conventions specified in the original prompt. - -""" - - def zero_shot_prompt(self, prompt: str) -> str: - """We try to zero-shot the task, maybe we're lucky!""" - return f""" -You are given the following prompt: - -{prompt} - - -The input data model is: - -{self.input_data_model.simplify_json_schema() if self.input_data_model is not None else 'N/A'} - - -The given input is: - -{str(self.input_data_model) if self.input_data_model is not None else 'N/A'} - - -The output data model is: - -{self.output_data_model.instruct_llm()} - - -Important guidelines: - -- The result of the task must be the output data model. -- Ensure the revised output is clear, accurate, and fully compliant with the original prompt. -- Maintain proper formatting and any required conventions specified in the original prompt. - -""" - - def forward(self, prompt: str, f_semantic_conditions: list[Callable] | None = None, *args, **kwargs): - if self.output_data_model is None: - raise ValueError("While the input data model is optional, the output data model must be provided. Please register it before calling the `forward` method.") - validation_context = kwargs.pop('validation_context', {}) - # Force JSON mode - kwargs["response_format"] = {"type": "json_object"} - logger.info("Initializing validation…") - if self.verbose: - for label, body in [ - ("Prompt", prompt), - ("Input data model", self.input_data_model.simplify_json_schema() if self.input_data_model else 'N/A'), - ("Output data model", self.output_data_model.simplify_json_schema()), - ]: - self.display_panel(body, title=label) - - # Zero shot the task - context = self.zero_shot_prompt(prompt=prompt) - json_str = super().forward(context, *args, **kwargs).value - - remedy_seeds = self.prepare_seeds(self.retry_params["tries"], **kwargs) - logger.info(f"Prepared {len(remedy_seeds)} remedy seeds for validation attempts…") - - result = None - errors = [] - for i in range(self.retry_params["tries"]): - logger.info(f"Attempt {i+1}/{self.retry_params['tries']}: Attempting validation…") - try: - result = self.output_data_model.model_validate_json(json_str, strict=True, context = validation_context) - if f_semantic_conditions is not None: - if not all(f(result) for f in f_semantic_conditions): - raise ValueError("Semantic validation failed!") - break - except Exception as e: - logger.info(f"Validation attempt {i+1} failed, pausing before retry…") - - self._pause() - - if isinstance(e, ValidationError): - error_str = self.simplify_validation_errors(e) - else: - error_str = str(e) - - errors.append(error_str) - - logger.error(f"Validation errors identified!") - if self.verbose: - self.display_panel( - "\n".join(errors) if self.accumulate_errors else error_str, - title=f"Validation Errors ({'accumulated errors' if self.accumulate_errors else 'last error'})", - border_style="red" - ) - - # Update remedy function context - logger.info("Updating remedy function context…") - context = self.remedy_prompt(prompt=prompt, output=json_str, errors="\n".join(errors) if self.accumulate_errors else error_str) - self.remedy_function.clear() - self.remedy_function.adapt(context) - if self.verbose: - self.display_panel( - self.remedy_function.dynamic_context, - title="New Context" - ) - - # Apply the remedy function - json_str = self.remedy_function(seed=remedy_seeds[i], **kwargs).value - logger.info("Applied remedy function with updated context!") - - if result is None: - logger.error(f"All validation attempts failed!") - raise TypeValidationError( - prompt=prompt, - result=json_str, - violations=errors, - ) - - logger.success("Validation completed successfully!") - # Clear artifacts from the remedy function - self.remedy_function.clear() - - return result - - -@beartype -class contract: - _default_remedy_retry_params = dict( - tries=5, - delay=0.5, - max_delay=15, - jitter=0.1, - backoff=2, - graceful=False - ) - - def __init__( - self, - pre_remedy: bool = False, - post_remedy: bool = True, - accumulate_errors: bool = False, - verbose: bool = False, - remedy_retry_params: dict[str, int | float | bool] = _default_remedy_retry_params, - ): - ''' - A contract class decorator inspired by DbC principles. It ensures that the function's input and output - adhere to specified data models both syntactically and semantically. This implementation includes retry - logic to handle transient errors and gracefully handle failures. - ''' - self.pre_remedy = pre_remedy - self.post_remedy = post_remedy - self.f_type_validation_remedy = TypeValidationFunction(accumulate_errors=accumulate_errors, verbose=verbose, retry_params=remedy_retry_params) - - if not verbose: - logger.disable(__name__) - else: - logger.enable(__name__) - - def _is_valid_input(self, input, *args, **kwargs): - if args: - logger.error("Positional arguments detected!") - raise ValueError("Positional arguments are not allowed! Please use keyword arguments instead.") - if input is None: - logger.error("No `input` argument provided!") - raise ValueError("Please provide an `input` argument.") - if not isinstance(input, LLMDataModel): - logger.error(f"Invalid input type: {type(input)}") - raise TypeError(f"Expected input to be of type `LLMDataModel`, got {type(input)}") - return True - - def _validate_input(self, wrapped_self, input, it, **remedy_kwargs): - logger.info("Starting input validation...") - if self.pre_remedy: - logger.info("Validating pre-conditions with remedy...") - if not hasattr(wrapped_self, 'pre'): - logger.error("Pre-condition function not defined!") - raise Exception("Pre-condition function not defined. Please define a `pre` method if you want to enforce pre-conditions through a remedy.") - - op_start = time.perf_counter() - try: - assert wrapped_self.pre(input) - logger.success("Pre-condition validation successful!") - return input - except Exception as e: - logger.error("Pre-condition validation failed!") - self.f_type_validation_remedy.register_expected_data_model(input, attach_to="output", override=True) - input = self.f_type_validation_remedy(wrapped_self.prompt, f_semantic_conditions=[wrapped_self.pre], **remedy_kwargs) - finally: - wrapped_self._contract_timing[it]["input_validation"] = time.perf_counter() - op_start - return input - else: - if hasattr(wrapped_self, 'pre'): - logger.info("Validating pre-conditions without remedy...") - op_start = time.perf_counter() - try: - assert wrapped_self.pre(input) - except Exception as e: - logger.error(f"Pre-condition validation failed (exception in pre): {str(e)}") - raise Exception(f"Pre-condition validation failed!\n{str(e)}") - finally: - wrapped_self._contract_timing[it]["input_validation"] = time.perf_counter() - op_start - logger.success("Pre-condition validation successful!") - return - logger.info("Skip; no pre-condition validation was required!") - - def _validate_output(self, wrapped_self, input, output, it, **remedy_kwargs): - logger.info("Starting output validation...") - self.f_type_validation_remedy.register_expected_data_model(input, attach_to="input", override=True) - self.f_type_validation_remedy.register_expected_data_model(output, attach_to="output", override=True) - - op_start = time.perf_counter() - try: - logger.info("Getting a valid output type...") - output = self.f_type_validation_remedy(wrapped_self.prompt, **remedy_kwargs) - except Exception as e: - logger.error(f"Type creation failed: {str(e)}") - raise Exception("Couldn't create a data model matching the output data model.") - finally: - wrapped_self._contract_timing[it]["output_validation"] = time.perf_counter() - op_start - logger.success("Type successfully created!") - - if self.post_remedy: - logger.info("Validating post-conditions with remedy...") - if not hasattr(wrapped_self, "post"): - logger.error("Post-condition function not defined!") - raise Exception("Post-condition function not defined. Please define a `post` method if you want to enforce post-conditions through a remedy.") - - op_start = time.perf_counter() - try: - assert wrapped_self.post(output) - logger.success("Post-condition validation successful!") - return output - except Exception as e: - logger.error("Post-condition validation failed!") - output = self.f_type_validation_remedy(wrapped_self.prompt, f_semantic_conditions=[wrapped_self.post], **remedy_kwargs) - finally: - wrapped_self._contract_timing[it]["output_validation"] += (time.perf_counter() - op_start) - logger.success("Post-condition validation successful!") - return output - else: - if hasattr(wrapped_self, "post"): - logger.info("Validating post-conditions without remedy...") - op_start = time.perf_counter() - try: - assert wrapped_self.post(output) - except Exception as e: - logger.error("Post-condition validation failed!") - raise Exception(f"Post-condition validation failed!\n{str(e)}") - finally: - wrapped_self._contract_timing[it]["output_validation"] = time.perf_counter() - op_start - logger.success("Post-condition validation successful!") - return - logger.info("Skip; no post-condition validation was required!") - - def _act(self, wrapped_self, input, it, **act_kwargs): - act_method = getattr(wrapped_self, 'act', None) - if not callable(act_method): - # Propagate the input if no act method is defined - return input - - logger.info(f"Executing 'act' method on {wrapped_self.__class__.__name__}…") - - act_sig = inspect.signature(act_method) - act_params_list = list(act_sig.parameters.values()) - - if not len(act_params_list) > 1: - raise TypeError(f"'act' method on {wrapped_self.__class__.__name__} must accept at least one input parameter after 'self'.") - - op_start = time.perf_counter() - try: - act_output = act_method(input, **act_kwargs) - except Exception as e: - logger.error(f"'act' method execution failed: {str(e)}") - raise Exception(f"'act' method execution failed!\n{str(e)}") - finally: - wrapped_self._contract_timing[it]["act_execution"] = time.perf_counter() - op_start - - if act_sig.return_annotation != inspect.Signature.empty and inspect.isclass(act_sig.return_annotation): - if not isinstance(act_output, act_sig.return_annotation): - raise TypeError(f"'act' method returned {type(act_output).__name__}, expected {act_sig.return_annotation.__name__}.") - - logger.success("'act' method executed successfully!") - return act_output - - def __call__(self, cls): - original_init = cls.__init__ - original_forward = cls.forward - - def __init__(wrapped_self, *args, **kwargs): - logger.info("Initializing contract...") - original_init(wrapped_self, *args, **kwargs) - - if not hasattr(wrapped_self, "prompt"): - logger.error("Prompt attribute not defined!") - raise Exception("Please define a static `prompt` attribute that describes what the contract must do.") - - wrapped_self.contract_successful = False - wrapped_self.contract_result = None - wrapped_self._contract_timing = defaultdict(dict) - logger.info("Contract initialization complete!") - - def wrapped_forward(wrapped_self, *args, **kwargs): - it = len(wrapped_self._contract_timing) # the len is the __call__ op_start - contract_start = time.perf_counter() - logger.info("Starting contract execution...") - # We first check if the input is valid - input = kwargs.pop("input", None) - assert self._is_valid_input(input) - maybe_payload = getattr(wrapped_self, "payload", None) - maybe_template = getattr(wrapped_self, "template") - if inspect.ismethod(maybe_template): - # `template` is a primitive in symbolicai case in which we actually don't have a template - maybe_template = None - - # Create validation kwargs that include all original kwargs plus payload and template - validation_kwargs = { - **kwargs, - "payload": maybe_payload, - "template_suffix": maybe_template - } - - sig = inspect.signature(original_forward) - output_type = sig.return_annotation - if output_type == inspect._empty: - logger.error("Missing return type annotation!") - raise ValueError("The contract requires a return type annotation.") - if not issubclass(output_type, LLMDataModel): - logger.error(f"Invalid return type: {output_type}") - raise ValueError("The return type annotation must be a subclass of `LLMDataModel`.") - - output = None - current_input = input - try: - # 1. Start with original input and apply pre-validation - maybe_new_input = self._validate_input(wrapped_self, current_input, it, **validation_kwargs) - if maybe_new_input is not None: - current_input = maybe_new_input - - # 2. Check if 'act' method exists and execute it - current_input = self._act(wrapped_self, current_input, it, **validation_kwargs) - - # 3. Validate output type and prepare for original_forward - output = self._validate_output(wrapped_self, current_input, output_type, it, **validation_kwargs) - wrapped_self.contract_successful = True - wrapped_self.contract_result = output - - except Exception as e: - logger.error(f"Contract execution failed in main path: {str(e)}") - wrapped_self.contract_successful = False - # contract_result remains None or its value before the exception. - # final_output remains None or its value before the exception. - # The finally block's execution of original_forward will determine the actual returned value. - finally: - # Execute the original forward method with appropriate input - logger.info("Executing original forward method...") - - # If contract was successful, use the processed input (after pre-validation and act, both optional) - # `current_input` at this stage is the result of the try block's processing up to the point of exception, - # or the full processing if successful. - # If contract failed, use original_input (fallback). - forward_input = current_input if wrapped_self.contract_successful else input - - # Prepare kwargs for original_forward - forward_kwargs = kwargs.copy() - forward_kwargs['input'] = forward_input - - try: - op_start = time.perf_counter() - output = original_forward(wrapped_self, **forward_kwargs) - finally: - wrapped_self._contract_timing[it]["forward_execution"] = time.perf_counter() - op_start - wrapped_self._contract_timing[it]["contract_execution"] = time.perf_counter() - contract_start - - if not isinstance(output, output_type): - logger.error(f"Output type mismatch: {type(output)}") - raise TypeError( - f"Expected output to be an instance of {output_type}, " - f"but got {type(output)}! Forward method must return an instance of {output_type}!" - ) - if not wrapped_self.contract_successful: - logger.warning("Contract validation failed!") - else: - logger.success("Contract validation successful!") - return output - - def contract_perf_stats(wrapped_self): - """Analyzes and prints timing statistics across all forward calls.""" - console = Console() - - num_calls = len(wrapped_self._contract_timing) - if num_calls == 0: - console.print("No contract executions recorded.") - return {} - - ordered_operations = [ - "input_validation", - "act_execution", - "output_validation", - "forward_execution", - "contract_execution" - ] - - stats = {} - for op in ordered_operations: - times = [] - for timing in wrapped_self._contract_timing.values(): - if op in timing: - times.append(timing[op]) - else: - times.append(0.0) - - non_zero_times = [t for t in times if t > 0] - actual_count = len(non_zero_times) - - total_time = sum(times) - mean_time = np.mean(non_zero_times) if non_zero_times else 0 - std_time = np.std(non_zero_times) if len(non_zero_times) > 1 else 0 - min_time = min(non_zero_times) if non_zero_times else 0 - max_time = max(non_zero_times) if non_zero_times else 0 - - stats[op] = { - 'count': actual_count, - 'total': total_time, - 'mean': mean_time, - 'std': std_time, - 'min': min_time, - 'max': max_time - } - - total_execution_time = stats['contract_execution']['total'] - for op in ordered_operations[:-1]: - if total_execution_time > 0: - stats[op]['percentage'] = (stats[op]['total'] / total_execution_time) * 100 - else: - stats[op]['percentage'] = 0 - - sum_tracked_times = sum(stats[op]['total'] for op in ordered_operations[:-1]) - overhead_time = total_execution_time - sum_tracked_times - overhead_percentage = (overhead_time / total_execution_time) * 100 if total_execution_time > 0 else 0 - - stats['overhead'] = { - 'count': num_calls, - 'total': overhead_time, - 'mean': overhead_time / num_calls if num_calls > 0 else 0, - 'std': 0, - 'min': 0, - 'max': 0, - 'percentage': overhead_percentage - } - - stats['contract_execution']['percentage'] = 100.0 - - table = Table( - title=f"Contract Execution Summary ({num_calls} Forward Calls)", - show_header=True - ) - table.add_column("Operation", style="cyan") - table.add_column("Count", justify="right", style="blue") - table.add_column("Total Time (s)", justify="right", style="green") - table.add_column("Mean (s)", justify="right", style="yellow") - table.add_column("Std Dev (s)", justify="right", style="magenta") - table.add_column("Min (s)", justify="right", style="red") - table.add_column("Max (s)", justify="right", style="red") - table.add_column("% of Total", justify="right", style="cyan") - - for op in ordered_operations[:-1]: - s = stats[op] - table.add_row( - op.replace("_", " ").title(), - str(s['count']), - f"{s['total']:.3f}", - f"{s['mean']:.3f}", - f"{s['std']:.3f}", - f"{s['min']:.3f}", - f"{s['max']:.3f}", - f"{s['percentage']:.1f}%" - ) - - s = stats['overhead'] - table.add_row( - "Overhead", - str(s['count']), - f"{s['total']:.3f}", - f"{s['mean']:.3f}", - f"{s['std']:.3f}", - f"{s['min']:.3f}", - f"{s['max']:.3f}", - f"{s['percentage']:.1f}%", - style="bold blue" - ) - - s = stats['contract_execution'] - table.add_row( - "Total Execution", - "N/A", - f"{s['total']:.3f}", - f"{s['mean']:.3f}", - f"{s['std']:.3f}", - f"{s['min']:.3f}", - f"{s['max']:.3f}", - "100.0%", - style="bold magenta" - ) - - console.print("\n") - console.print(table) - console.print("\n") - - return stats - - cls.__init__ = __init__ - cls.forward = wrapped_forward - cls.contract_perf_stats = contract_perf_stats - - return cls - - -class BaseStrategy(TypeValidationFunction): - def __init__(self, data_model: BaseModel, *args, **kwargs): - super().__init__( - retry_params=dict(tries=NUM_REMEDY_RETRIES, delay=0.5, max_delay=15, backoff=2, jitter=0.1, graceful=False), - **kwargs, - ) - super().register_expected_data_model(data_model, attach_to="output") - self.logger = logging.getLogger(__name__) - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - pass - - def forward(self, *args, **kwargs): - result = super().forward( - *args, - payload=self.payload, - template_suffix=self.template, - response_format={"type": "json_object"}, - **kwargs, - ) - return result - - @property - def payload(self): - return None - - @property - def static_context(self): - raise NotImplementedError() - - @property - def template(self): - return "{{fill}}" - - -class Strategy(Expression): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.logger = logging.getLogger(__name__) - - def __new__(self, module: str, *args, **kwargs): - self._module = module - self.module_path = 'symai.extended.strategies' - return Strategy.load_module_class(self.module) diff --git a/symbolicai-main/symbolicai-main/symai/symbol.py b/symbolicai-main/symbolicai-main/symai/symbol.py deleted file mode 100644 index 3c7b7960b517d168d588b48b6de03dc9b503ea60..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/symbol.py +++ /dev/null @@ -1,1194 +0,0 @@ -import copy -import html -import json -from json import JSONEncoder -from typing import (Any, Callable, Dict, Generic, Iterator, List, Optional, - Tuple, Type, TypeVar) - -import numpy as np -from box import Box - -from . import core -from .ops import SYMBOL_PRIMITIVES - -T = TypeVar('T') - - -class SymbolEncoder(JSONEncoder): - def default(self, o): - ''' - Encode a Symbol instance into its dictionary representation. - - Args: - sym (Symbol): The Symbol instance to encode. - - Returns: - dict: The dictionary representation of the Symbol instance. - ''' - if isinstance(o, Symbol): - return o.__getstate__() - return JSONEncoder.default(self, o) - - -class Metadata(object): - # create a method that allow to dynamically assign a attribute if not in __dict__ - # example: metadata = Metadata() - # metadata.some_new_attribute = 'some_value' - # metadata.some_new_attribute - @property - def keys(self): - return self.__dict__.keys() - - def __getattr__(self, name): - ''' - Get a metadata attribute by name. - - Args: - name (str): The name of the metadata attribute to get. - - Returns: - Any: The value of the metadata attribute. - ''' - return self.__dict__.get(name) - - def __setattr__(self, name, value): - ''' - Set a metadata attribute by name. - - Args: - name (str): The name of the metadata attribute to set. - value (Any): The value of the metadata attribute. - ''' - self.__dict__[name] = value - - def __delattr__(self, name): - ''' - Delete a metadata attribute by name. - - Args: - name (str): The name of the metadata attribute to delete. - ''' - del self.__dict__[name] - - def __getitem__(self, name): - ''' - Get a metadata attribute by name. - - Args: - name (str): The name of the metadata attribute to get. - - Returns: - Any: The value of the metadata attribute. - ''' - return self.__getattr__(name) - - def __setitem__(self, name, value): - ''' - Set a metadata attribute by name. - - Args: - name (str): The name of the metadata attribute to set. - value (Any): The value of the metadata attribute. - ''' - self.__setattr__(name, value) - - def __delitem__(self, name): - ''' - Delete a metadata attribute by name. - - Args: - name (str): The name of the metadata attribute to delete. - ''' - self.__delattr__(name) - - def __str__(self) -> str: - ''' - Get the string representation of the Symbol's value. - - Returns: - str: The string representation of the Symbol's value. - ''' - _val = '' - if self.value is not None: - _val += str(self.value) - return _val + f"Properties({str({k: str(v) for k, v in self.__dict__.items() if not k.startswith('_')})})" - - def __repr__(self) -> str: - ''' - Get the representation of the Symbol object as a string. - - Returns: - str: The representation of the Symbol object. - ''' - # class with full path - class_ = self.__class__.__module__ + '.' + self.__class__.__name__ - hex_ = hex(id(self)) - from_symbol = f' from {self.symbol_type.__module__}.{self.symbol_type.__name__}' if self.symbol_type else '' - return f'' - - -class Linker(Metadata): - def keys(self) -> List[str]: - ''' - Get all keys of the linker. - - Returns: - List[str]: All keys of the linker. - ''' - return list(self.results.keys()) - - def values(self) -> List[Any]: - ''' - Get all values of the linker. - - Returns: - List[Any]: All values of the linker. - ''' - return list(self.results.values()) - - def find(self, name: str, single: bool = True, strict: bool = False) -> Any: - ''' - Find a result in the linker. - - Args: - name (str): The name of the result to find. - single (bool): Whether to return a single result or a list of results. Defaults to True. - strict (bool): Whether to match the name exactly or not. Defaults to False. - - Returns: - Any: The result. - ''' - # search all results and return the first one that matches the name - res = [] - for k in list(self.results.keys()): - match_ = lambda k, name: str(name).lower() in str(k).lower() if not strict else str(name) == str(k) - if match_(k, name): - res.append(self.results[k]) - if single: - assert len(res) == 1, f'Found {len(res)} results for name {name}. Expected 1.' - if len(res) == 0: - return None - elif len(res) == 1: - return res[0] - return res - - -class PropertyReservedError(AttributeError): - def __init__(self, property_name): - self.property_name = property_name - super().__init__(f"Cannot set reserved property '{property_name}'. This property is defined in the 'Symbol' base class and cannot be assigned.") - - -class SymbolMeta(type): - """ - Metaclass to unify metaclasses of mixed-in primitives. - """ - def __call__(cls, *args, **kwargs): - obj = type.__call__(cls, *args, **kwargs) - obj.__post_init__(*args, **kwargs) - return obj - - def __instancecheck__(cls, obj): - if str(obj.__class__) == str(cls): - return True - return super().__instancecheck__(obj) - - def __new__(mcls, name, bases, attrs): - """ - Create a new class with a unified metaclass. - """ - # create a new cls type that inherits from Symbol and the mixin primitive types - cls = type.__new__(mcls, name, bases, attrs) - # inherit the base class module for dynamic type creation - if '__module__' in attrs: - cls.__module__ = attrs['__module__'] - elif len(bases) > 0: - cls.__module__ = bases[0].__module__ - return cls - - -class Symbol(Generic[T], metaclass=SymbolMeta): - _mixin = True - _primitives = SYMBOL_PRIMITIVES - _metadata = Metadata() - _metadata._primitives = {} - _dynamic_context: Dict[str, List[str]] = {} - _RESERVED_PROPERTIES = {'graph', 'linker', 'parent', 'children', 'metadata', 'value', 'root', 'nodes', 'edges', 'global_context', 'static_context', 'dynamic_context', 'shape'} - - def __init__(self, *value, static_context: Optional[str] = '', dynamic_context: Optional[str] = None, **kwargs) -> None: - ''' - Initialize a Symbol instance with a specified value. Unwraps nested symbols. - - Args: - value (Optional[Any]): The value of the symbol. Can be a single value or multiple values. - static_context (Optional[str]): The static context of the symbol. Defaults to an empty string. - - Attributes: - value (Any): The value of the symbol. - metadata (Optional[Dict[str, Any]]): The metadata associated with the symbol. - ''' - super().__init__() - self._value = None - # store kwargs for new symbol instance type passing - self._kwargs = { - 'static_context': static_context, - **kwargs - } - self._metadata = Metadata() # use global metadata by default - self._metadata.symbol_type = type(self) - self._parent = None - self._children = [] - self._static_context = static_context - self._dynamic_context = dynamic_context or Symbol._dynamic_context - # if value is a single value, unwrap it - _value = self._unwrap_symbols_args(*value) - self._value = _value - # construct dependency graph for symbol - self._construct_dependency_graph(*value) - - def __post_init__(self, *args, **kwargs): # this is called at the end of __init__ - ''' - Post-initialization method that is called at the end of the __init__ method. - ''' - def _func(k, v): - # check if property is of type Symbol and not private and a class variable (not a function) - if isinstance(v, Symbol) and not k.startswith('_') and not v is self: - v._parent = self - self._children.append(v) - # else if iterable, check if it contains symbols - elif (isinstance(v, list) or isinstance(v, tuple)) and not k.startswith('_'): - for i in v: - _func(k, i) - - # analyze all self. properties if they are of type Symbol and add their parent and root - for k, v in self.__dict__.items(): - _func(k, v) - - def _unwrap_symbols_args(self, *args, nested: bool = False) -> Any: - if len(args) == 0: - return None - # check if args is a single value - elif len(args) == 1: - # get the first args value - value = args[0] - - # if the value is a primitive, store it as is - if isinstance(value, str) or isinstance(value, int) or isinstance(value, float) or isinstance(value, bool): - pass - - # if the value is a symbol, unwrap it - elif isinstance(value, Symbol): - # if not nested, copy the symbol's value, metadata, parent, and children - if not nested: - self._metadata = value.metadata - self._static_context = value.static_context - self._kwargs = value._kwargs - # unwrap the symbol's value - value = value.value - - # if the value is a list, tuple, dict, or set, unwrap all nested symbols - elif isinstance(value, list) or isinstance(value, dict) or \ - isinstance(value, set) or isinstance(value, tuple): - - if isinstance(value, list): - value = [self._unwrap_symbols_args(v, nested=True) for v in value] - - elif isinstance(value, dict): - value = {self._unwrap_symbols_args(k, nested=True): self._unwrap_symbols_args(v, nested=True) for k, v in value.items()} - - elif isinstance(value, set): - value = {self._unwrap_symbols_args(v, nested=True) for v in value} - - elif isinstance(value, tuple): - value = tuple([self._unwrap_symbols_args(v, nested=True) for v in value]) - - return value - - elif len(args) > 1: - return [self._unwrap_symbols_args(a, nested=True) if isinstance(a, Symbol) else a for a in args] - - def _construct_dependency_graph(self, *value): - ''' - Construct a dependency graph for the symbol. - - Args: - value (Any): The value of the symbol. - ''' - # for each value - for v in value: - if isinstance(v, Symbol) and not v is self: - # new instance becomes child of previous instance - v._parent = self - # add new instance to children of previous instance - self._children.append(v) - - def __new__(cls, *args, - mixin: Optional[bool] = None, - primitives: Optional[List[Type]] = None, - callables: Optional[List[Tuple[str, Callable]]] = None, - semantic: bool = False, - **kwargs) -> "Symbol": - ''' - Create a new Symbol instance. - - Args: - *args: Variable length argument list. - mixin (Optional[bool]): Whether to mix in the SymbolOperatorPrimitives class. Defaults to None. - primitives (Optional[List[Type]]): A list of primitive classes to mix in. Defaults to None. - callables (Optional[List[Callable]]): A list of dynamic primitive functions to mix in. Defaults to None. - semantic (bool): Whether or not the symbol should be semantic; enforces the use of a neuro-symbolic engine. Defaults to False. - **kwargs: Arbitrary keyword arguments. - - Returns: - Symbol: The new Symbol instance. - ''' - use_mixin = mixin if mixin is not None else cls._mixin - standard_primitives = primitives is None - primitives = primitives if not standard_primitives else cls._primitives - if not isinstance(primitives, list): - primitives = [primitives] - # Initialize instance as a combination of Symbol and the mixin primitive types - if use_mixin: - # create a new cls type that inherits from Symbol and the mixin primitive types - cls = SymbolMeta(cls.__name__, (cls,) + tuple(primitives), {}) - obj = super().__new__(cls) - # store to inherit when creating new instances - obj._kwargs = { - 'mixin': use_mixin, - 'primitives': primitives, - 'callables': callables, - 'semantic': semantic, - **kwargs - } - # configure standard primitives - if use_mixin and standard_primitives: - # allow to iterate over iterables for neuro-symbolic values - if semantic: - obj.__semantic__ = True - # If metatype has additional runtime primitives, add them to the instance - if Symbol._metadata._primitives is not None: - for prim_name in list(Symbol._metadata._primitives.keys()): - # create a new function that binds the instance to the callable - setattr(obj, prim_name, Symbol._metadata._primitives[prim_name](obj)) - # If has additional runtime callables, add them to the instance - if callables is not None: - if not isinstance(callables, list): - callables = [callables] - for call_name, call_func in callables: - # create a new function that binds the instance to the callable - setattr(obj, call_name, call_func(obj)) - return obj - - def __setattr__(self, name: str, value: Any) -> None: - ''' - Set the attribute of the Symbol's value with the specified name. - - Args: - name (str): The name of the attribute to set for the Symbol's value. - value (Any): The value of the attribute to set for the Symbol's value. - - Raises: - PropertyReservedError: If the property is reserved and cannot be set. - ''' - if name in self._RESERVED_PROPERTIES: - raise PropertyReservedError(name) - super().__setattr__(name, value) - - def __getattr__(self, name: str) -> Any: - ''' - Get the attribute of the Symbol's value with the specified name or the attribute of the Symbol value with the specified name. - - Args: - name (str): The name of the attribute to get from the Symbol's value. - - Returns: - Any: The attribute of the Symbol's value with the specified name. - ''' - try: - # try to get attribute from current instance - if name in self.__dict__: - return self.__dict__[name] - value = self.value if self.value is not None else None - if isinstance(value, Exception): - raise value - raise AttributeError(f' or nested value of {str(type(value))} have no attribute \'{name}\'') - except AttributeError as ex: - # if has attribute and is public function - if hasattr(self.value, name) and not name.startswith('_'): - return getattr(self.value, name) - raise ex - - def __array__(self, dtype=None): - ''' - Get the numpy array representation of the Symbol's value. - - Returns: - np.ndarray: The numpy array representation of the Symbol's value. - ''' - return self.embedding.astype(dtype, copy=False) - - def __buffer__(self, flags=0): - ''' - Get the buffer of the Symbol's value. - - Args: - flags (int, optional): The flags for the buffer. Defaults to 0. - - Returns: - memoryview: The buffer of the Symbol's value. - ''' - return memoryview(self.embedding) - - @staticmethod - def symbols(*values) -> List["Symbol"]: - ''' - Create a list of Symbol instances from a list of values. - - Args: - values (List[Any]): The list of values to create Symbol instances from. - - Returns: - List[Symbol]: The list of Symbol instances. - ''' - return [Symbol(value) for value in values] - - def __reduce__(self): - ''' - This method is called by pickle to serialize the object. - It returns a tuple that contains: - - A callable object that when called produces a new object (e.g., the class of the object) - - A tuple of arguments for the callable object - - Optionally, the state which will be passed to the object’s `__setstate__` method - - Returns: - tuple: A tuple containing the callable object, the arguments for the callable object, and the state of the object. - ''' - # Get the state of the object - state = self.__getstate__() - - # We create a simple tuple of primitives and their names to be able to pickle them. - # Note: This assumes that the primitives are pickleable (it can be a limitation). - primitives = [(primitive, primitive.__name__) for primitive in self._primitives] - - # Get the base class for reconstruction - base_cls = self.__class__.__bases__[0] - - # The __reduce__ method returns: - # - A callable object that when called produces a new object (e.g., the class of the object) - # - A tuple of arguments for the callable object - # - Optionally, the state which will be passed to the object’s `__setstate__` method - return (self._reconstruct_class, (base_cls, self._mixin, primitives), state) - - def __reduce_ex__(self, protocol): - return self.__reduce__() - - # This will be called by pickle with the info from __reduce__ to recreate the dynamic class - @staticmethod - def _reconstruct_class(base_cls, use_mixin, primitives_info): - ''' - Reconstruct the class from the serialized state. - - Args: - base_cls (Type): The base class of the Symbol. - use_mixin (bool): Whether to mix in the SymbolOperatorPrimitives class. - primitives_info (List[Tuple[Type, str]]): A list of primitive classes and their names. - - Returns: - Type: The reconstructed class. - ''' - if use_mixin: - # Convert primitive info tuples back to types - primitives = [primitive for primitive, name in primitives_info] - # Create new cls with UnifiedMeta metaclass - cls = SymbolMeta(base_cls.__name__, (base_cls,) + tuple(primitives), {}) - obj = cls() - return obj - return base_cls() - - def __getstate__(self) -> Dict[str, Any]: - ''' - Get the state of the symbol for serialization. - - Returns: - dict: The state of the symbol. - ''' - state = vars(self).copy() - state.pop('_metadata', None) - state.pop('_parent', None) - state.pop('_children', None) - return state - - def __setstate__(self, state) -> None: - ''' - Set the state of the symbol for deserialization. - - Args: - state (dict): The state to set the symbol to. - ''' - vars(self).update(state) - self._metadata = Metadata() - self._metadata.symbol_type = type(self) - self._kwargs = self._kwargs - self._parent = None - self._children = [] - - def json(self) -> Dict[str, Any]: - ''' - Get the json-serializable dictionary representation of the Symbol instance. - - Returns: - dict: The json-serializable dictionary representation of the Symbol instance. - ''' - return self.__getstate__() - - def serialize(self): - ''' - Encode an Symbol instance into its dictionary representation. - - Args: - obj (Symbol): The Expression instance to encode. - - Returns: - dict: The dictionary representation of the Symbol instance. - ''' - return json.dumps(self, cls=SymbolEncoder) - - def _to_symbol(self, value: Any, **kwargs) -> "Symbol": - ''' - Convert a value to a Symbol instance. - - Args: - value (Any): The value to convert to a Symbol instance. - - Returns: - Symbol: The Symbol instance. - ''' - type_ = Symbol - if isinstance(value, type_): - return value - # inherit kwargs for new symbol instance - kwargs = {**self._kwargs, **kwargs} - sym = type_(value, **kwargs) - return sym - - def _to_type(self, value: Any, **kwargs) -> "Symbol": - ''' - Convert a value to its own type instance. - - Args: - value (Any): The value to convert to its own type instance. - - Returns: - Type: The type instance. - ''' - type_ = type(self) - if isinstance(value, type_): - return value - # inherit kwargs for new symbol instance - kwargs = {**self._kwargs, **kwargs} - sym = type_(value, **kwargs) - return sym - - @property - def _symbol_type(self) -> "Symbol": - ''' - Get the type of the Symbol instance. - - Returns: - Symbol: The type of the Symbol instance. - ''' - return Symbol - - def __hash__(self) -> int: - ''' - Get the hash value of the symbol. - - Returns: - int: The hash value of the symbol. - ''' - return str(self.value).__hash__() - - @property - def metadata(self) -> Dict[str, Any]: - ''' - Get the metadata associated with the symbol. - - Returns: - Dict[str, Any]: The metadata associated with the symbol. - ''' - return self._metadata - - @property - def value(self) -> Any: - ''' - Get the value of the symbol. - - Returns: - Any: The value of the symbol. - ''' - return self._value - - @property - def global_context(self) -> str: - ''' - Get the global context of the symbol, which consists of the static and dynamic context. - - Returns: - str: The global context of the symbol. - ''' - return (self.static_context, self.dynamic_context) - - @property - def static_context(self) -> str: - ''' - Get the static context of the symbol which is defined by the user when creating a symbol subclass. - - Returns: - str: The static context of the symbol. - ''' - return f'{self._static_context}' if self._static_context else '' - - @static_context.setter - def static_context(self, value: str): - ''' - Set the static context of the symbol which is defined by the user when creating a symbol subclass. - ''' - self._static_context = value - - @property - def dynamic_context(self) -> str: - ''' - Get the dynamic context which is defined by the user at runtime. - It helps to alter the behavior of the symbol at runtime. - - Returns: - str: The dynamic context associated with this symbol type. - ''' - # if dynamic context is manually set to a string, return it - if isinstance(self._dynamic_context, str): - return self._dynamic_context - type_ = str(type(self)) - if type_ not in Symbol._dynamic_context: - Symbol._dynamic_context[type_] = [] - return '' - dyn_ctxt = Symbol._dynamic_context[type_] - if len(dyn_ctxt) == 0: - return '' - sym_val = [str(v.value) if isinstance(v, Symbol) else str(v) for v in dyn_ctxt] - val = '\n'.join(sym_val) - return f'\n{val}' if val else '' - - @property - def root(self) -> "Symbol": - ''' - Get the root of the symbol. - - Returns: - Symbol: The root of the symbol. - ''' - root = self - while root.parent is not None: - root = root.parent - return root - - @property - def nodes(self) -> List["Symbol"]: - ''' - Get all nodes descending recursively from the symbol. - - Returns: - List[Symbol]: All nodes of the symbol. - ''' - def _func(node, nodes): - nodes.append(node) - for child in node.children: - _func(child, nodes) - - nodes = [] - _func(self, nodes) - return nodes - - @property - def edges(self) -> List[tuple]: - ''' - Get all edges descending recursively from the symbol. - - Returns: - List[tuple]: All edges of the symbol. - ''' - def _func(node, edges): - for child in node.children: - edges.append((node, child)) - _func(child, edges) - - edges = [] - _func(self, edges) - return edges - - @property - def graph(self) -> (List["Symbol"], List[tuple]): - ''' - Get the graph representation of the symbol. - - Returns: - List[Symbol], List[tuple]: The nodes and edges of the symbol. - ''' - return self.nodes, self.edges - - @property - def linker(self) -> List["Symbol"]: - ''' - Returns the link object metadata by descending recursively from the root of the symbol to the root_link object. - - Returns: - List[Symbol]: All results of the symbol. - ''' - return self.root.metadata.root_link - - @property - def parent(self) -> "Symbol": - ''' - Get the parent of the symbol. - - Returns: - Symbol: The parent of the symbol. - ''' - return self._parent - - @property - def children(self) -> List["Symbol"]: - ''' - Get the children of the symbol. - - Returns: - List[Symbol]: The children of the symbol. - ''' - return self._children - - def _root_link(self, sym: Any, **kwargs) -> Any: - ''' - Call the forward method and assign the result to the graph value attribute. - - Args: - res (Any): The result of the forward method. - **kwargs: Arbitrary keyword arguments. - - Returns: - Any: The result of the forward method. - ''' - # transport results to the root node for global access - if not self is self.root and not self.metadata.detach: - ref = self.root.metadata - if ref.root_link is None: - ref.root_link = Linker() - if ref.root_link.results is None: - ref.root_link.results = {} - prev = None - if len(ref.root_link.results) > 0: - prev = list(ref.root_link.results.values())[-1] # get previous result - # create new symbol to avoid circular references - res_ = Symbol(sym) - if prev is not None and not prev is res_.root: - prev.children.append(res_.root) - res_.root._parent = prev - ref.root_link.results[self.__repr__()] = res_ - - def adapt(self, context: str, types: List[Type] = []) -> None: - ''' - Update the dynamic context with a given runtime context. - - Args: - context (str): The context to be added to the dynamic context. - type (Type): The type used to update the dynamic context - - ''' - if not isinstance(types, list): - types = [types] - if len(types) == 0: - types = [type(self)] - - for type_ in types: - type_ = str(type_) - if type_ not in Symbol._dynamic_context: - Symbol._dynamic_context[type_] = [] - - Symbol._dynamic_context[type_].append(str(context)) - - def clear(self, types: List[Type] = []) -> None: - ''' - Clear the dynamic context associated with this symbol type. - ''' - if not isinstance(types, list): - types = [types] - if len(types) == 0: - types = [type(self)] - - for type_ in types: - type_ = str(type_) - if type_ not in Symbol._dynamic_context: - Symbol._dynamic_context[type_] = [] - return - - Symbol._dynamic_context[type_].clear() - - def __len__(self) -> int: - ''' - Get the length of the value of the Symbol. - - Returns: - int: The length of the value of the Symbol. - ''' - return len(self.value) - - @property - def shape(self) -> tuple: - ''' - Get the shape of the value of the Symbol. - - Returns: - tuple: The shape of the value of the Symbol. - ''' - return self.value.shape - - def __str__(self) -> str: - ''' - Get the string representation of the Symbol's value. - - Returns: - str: The string representation of the Symbol's value. - ''' - if self.value is None: - return '' - elif isinstance(self.value, list) or isinstance(self.value, np.ndarray) or isinstance(self.value, tuple): - return str([str(v) for v in self.value]) - elif isinstance(self.value, dict): - return str({k: str(v) for k, v in self.value.items()}) - elif isinstance(self.value, set): - return str({str(v) for v in self.value}) - else: - return str(self.value) - - def __repr__(self, simplified: bool = False) -> str: - ''' - Get the representation of the Symbol object as a string. - - Returns: - str: The representation of the Symbol object. - ''' - # class with full path - class_ = self.__class__.__module__ + '.' + self.__class__.__name__ - hex_ = hex(id(self)) - val = str(self.value) - # only show first n characters of value and then add '...' and the last x characters - if len(val) > 50: - val = val[:25] + ' ... ' + val[-20:] - return f'(value={val})' if not simplified else f'{class_} at {hex_}' - - def _repr_html_(self) -> str: - ''' - Get the HTML representation of the Symbol's value. - - Returns: - str: The HTML representation of the Symbol's value. - ''' - return html.escape(self.__repr__()) - - def __iter__(self) -> Iterator: - ''' - Get an iterator for the Symbol's value. - If the Symbol's value is a list, tuple, or numpy.ndarray, iterate over the elements. Otherwise, create a new list with a single item and iterate over the list. - - Returns: - Iterator: An iterator for the Symbol's value. - ''' - if isinstance(self.value, list) or isinstance(self.value, tuple) or isinstance(self.value, np.ndarray): - return iter(self.value) - - return self.list('item').value.__iter__() - - def __reversed__(self) -> Iterator: - ''' - Get a reversed iterator for the Symbol's value. - - Returns: - Iterator: A reversed iterator for the Symbol's value. - ''' - return reversed(list(self.__iter__())) - - def __next__(self) -> Any: - ''' - Get the next item in the iterable value of the Symbol. - If it is not a list, tuple, or numpy array, the method falls back to using the @core.next() decorator, which retrieves and returns the next item using core functions. - - Returns: - Symbol: The next item in the iterable value of the Symbol. - - Raises: - StopIteration: If the iterable value reaches its end. - ''' - return next(self.__iter__()) - - def primitive(self, name: str, callable: callable) -> None: - ''' - Set a primitive function to the Symbol instance. - - Args: - - callable (callable): The primitive function to set. - scope (Union['instance', 'type', 'class'], optional): The scope of the primitive function. Defaults to 'instance'. - - Args: - callable (callable): The primitive function to set. - ''' - def _func(*args, **kwargs): - return callable(self, *args, **kwargs) - setattr(self, name, _func) - - @staticmethod - def _global_primitive(name: str, callable: callable) -> None: - ''' - Set a primitive function to the Symbol class. - - Args: - callable (callable): The primitive function to set. - ''' - def _func(obj): - return lambda *args, **kwargs: callable(obj, *args, **kwargs) - Symbol._metadata._primitives[name] = _func - - -# TODO: Workaround for Python bug to enable runtime assignment of lambda function to new Symbol objects. -# Currently creating multiple lambda functions within class __new__ definition only links last lambda function to all new Symbol attribute assignments. -# Need to contact Python developers to fix this bug. -class Call(object): - def __new__(self, name, callable: Callable) -> Any: - ''' - Prepare a callable for use in a Symbol instance. - - Args: - callable (Callable): The callable to prepare. - - Returns: - Callable: The prepared callable. - ''' - def _func(obj): - return lambda *args, **kwargs: callable(obj, *args, **kwargs) - return (name, _func) - - -class GlobalSymbolPrimitive(object): - def __new__(self, name, callable: Callable) -> Any: - ''' - Prepare a callable for use in a Symbol instance. - - Args: - callable (Callable): The callable to prepare. - - Returns: - Callable: The prepared callable. - ''' - Symbol._global_primitive(name, callable) - - -class ExpressionEncoder(JSONEncoder): - def default(self, o): - if isinstance(o, Expression): - return o.__getstate__() - return JSONEncoder.default(self, o) - - -class Expression(Symbol): - - def __init__(self, value = None, *args, **kwargs): - ''' - Create an Expression object that will be evaluated lazily using the forward method. - - Args: - value (Any, optional): The value to be stored in the Expression object. Usually not provided as the value - is computed using the forward method when called. Defaults to None. - *args: Variable length argument list. - **kwargs: Arbitrary keyword arguments. - ''' - super().__init__(value, *args, **kwargs) - self._sym_return_type = type(self) - - def __call__(self, *args, **kwargs) -> Any: - ''' - Evaluate the expression using the forward method and assign the result to the value attribute. - - Args: - *args: Variable length argument list. - **kwargs: Arbitrary keyword arguments. - - Returns: - Any: The result of the forward method. - ''' - # evaluate the expression - res = self.forward(*args, **kwargs) - # store the result in the root node and link it to the previous result - self._root_link(res, **kwargs) - return res - - def __getstate__(self): - state = super().__getstate__().copy() - state.pop('_sym_return_type', None) - return state - - def __setstate__(self, state): - self.__dict__.update(state) - self._sym_return_type = type(self) - - def __json__(self): - ''' - Get the json-serializable dictionary representation of the Expression instance. - - Returns: - dict: The json-serializable dictionary representation of the Expression instance. - ''' - return self.__getstate__() - - def serialize(self): - ''' - Encode an Expression instance into its dictionary representation. - - Args: - obj (Expression): The Expression instance to encode. - - Returns: - dict: The dictionary representation of the Expression instance. - ''' - return json.dumps(self, cls=ExpressionEncoder) - - @property - def sym_return_type(self) -> Type: - ''' - Returns the casting type of this expression. - - Returns: - Type: The casting type of this expression. Defaults to the current Expression-type. - ''' - return self._sym_return_type - - @sym_return_type.setter - def sym_return_type(self, type: Type) -> None: - ''' - Sets the casting type of this expression. - - Args: - type (Type): The casting type of this expression. - ''' - self._sym_return_type = type - - def forward(self, *args, **kwargs) -> Symbol: #TODO make reserved kwargs with underscore: ____ - ''' - Needs to be implemented by subclasses to specify the behavior of the expression during evaluation. - - Args: - *args: Variable length argument list. - **kwargs: Arbitrary keyword arguments. - - Returns: - Symbol: The evaluated result of the implemented forward method. - ''' - raise NotImplementedError() - - @staticmethod - def command(engines: List[str] = ['all'], **kwargs) -> 'Symbol': - ''' - Execute command(s) on engines. - - Args: - engines (List[str], optional): The list of engines on which to execute the command(s). Defaults to ['all']. - **kwargs: Arbitrary keyword arguments to be used by the core.command decorator. - - Returns: - Symbol: An Expression object representing the command execution result. - ''' - @core.command(engines=engines, **kwargs) - def _func(_): - pass - return Expression(_func(Expression())) - - @staticmethod - def register(engines: Dict[str, Any], **kwargs) -> 'Symbol': - ''' - Configure multiple engines. - - Args: - engines (Dict[str, Any]): A dictionary containing engine names as keys and their configurations as values. - **kwargs: Arbitrary keyword arguments to be used by the core.register decorator. - - Returns: - Symbol: An Expression object representing the register result. - ''' - @core.register(engines=engines, **kwargs) - def _func(_): - pass - return Expression(_func(Expression())) - - def copy(self) -> Any: - ''' - Returns a deep copy of the own object. - - Returns: - Any: A deep copy of the own object. - ''' - return copy.deepcopy(self) - - @staticmethod - def prompt(message: str, **kwargs) -> 'Symbol': - ''' - General raw input prompt method. - - Args: - message (str): The prompt message for describing the task. - **kwargs: Arbitrary keyword arguments to be used by the core.prompt decorator. - - Returns: - Symbol: An Expression object representing the prompt result. - ''' - @core.prompt(message=message, **kwargs) - def _func(_): - pass - return Expression(_func(None)) - - -class Result(Expression): - def __init__(self, value = None, *args, **kwargs): - ''' - Create a Result object that stores the results operations, including the raw result, value and metadata, if any. - - Args: - value (Any, optional): The value to be stored in the Expression object. Usually not provided as the value - is computed using the forward method when called. Defaults to None. - *args: Variable length argument list. - **kwargs: Arbitrary keyword arguments. - ''' - super().__init__(value, **kwargs) # value is the same as raw when initialized, however, it can be changed later - self._sym_return_type = type(self) - try: - # try to make the values easily accessible - self.raw = Box(value) - except: - # otherwise, store the unprocessed view - self.raw = value - - @property - def value(self) -> Any: - ''' - Get the value of the symbol. - - Returns: - Any: The value of the symbol. - ''' - return self._value - - @value.setter - def value(self, value: Any) -> None: - ''' - Set the value of the Result object. - - Args: - value (Any): The value to set the Result object to. - ''' - self._value = value diff --git a/symbolicai-main/symbolicai-main/symai/symsh.md b/symbolicai-main/symbolicai-main/symai/symsh.md deleted file mode 100644 index 36b7cd969b6a3b81f147b6c133ef94172293eed1..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/symsh.md +++ /dev/null @@ -1,23 +0,0 @@ -"LLM Command Usage and Detail: - -llm (language model) processing is initiated with specific start flags `'`, `"` and `` ` `` and optionally preceded by `.`, `!`, or `?`. - -1. Normal Mode: `'`, `"` and `` ` `` - Usage: 'Your Query' or "Your Query" or `Your Query` - These commands send 'Your Query' to sym's language model and return the result. - -2. Stateful Mode: `.'`, `."` and `.` - Usage: .'Your Query' or ."Your Query" or .`Your Query` - These commands create a stateful conversation with sym’s language models. Once you have initiated a stateful conversation - with `.`, continuing with queries using `.` will result in the conversation maintaining a context from all previous queries - and responses. - -3. Overwrite Mode: `!'`, `!"`, `!` - Usage: !'Your Query' or !"Your Query" or !`Your Query` - These commands function as their normal or stateful counterparts, but also overwrite the existing conversation_state.pickle. - -4. Search Mode: `?'`, `?"`, `?` - Usage: ?'Your Query' or ?"Your Query" or ?`Your Query` - This command sends 'Your Query' to sym's internal search engine and the results are returned in the shell. - -Note: The use of `'`, `"` or `` ` `` to wrap 'Your Query' does not impact the functionality of the command." \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/symai/utils.py b/symbolicai-main/symbolicai-main/symai/utils.py deleted file mode 100644 index 47288901c2c5b42885195e3958d110aabddee7d6..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/symai/utils.py +++ /dev/null @@ -1,250 +0,0 @@ -from __future__ import annotations - -import base64 -import inspect -import json -import os -import warnings -from dataclasses import dataclass - -import cv2 -import httpx -import numpy as np -from box import Box -from PIL import Image -from transformers.models.detr.image_processing_detr_fast import defaultdict - -from .misc.console import ConsoleStyle - - -def encode_media_frames(file_path): - ext = file_path.split('.')[-1] - if ext.lower() == 'jpg' or ext.lower() == 'jpeg' or ext.lower() == 'png' or ext.lower() == 'webp': - if file_path.startswith('http'): - return encode_image_url(file_path) - return encode_image_local(file_path) - elif ext.lower() == 'gif': - if file_path.startswith('http'): - raise ValueError("GIF files from URLs are not supported. Please download the file and try again.") - - ext = 'jpeg' - # get frames from gif - base64Frames = [] - with Image.open(file_path) as frames: - for frame in range(frames.n_frames): - frames.seek(frame) - # get the image as bytes in memory (using BytesIO) - current_frame = np.array(frames.convert('RGB')) - _, buffer = cv2.imencode(".jpg", current_frame) - base64Frames.append(base64.b64encode(buffer).decode("utf-8")) - return base64Frames, ext - elif ext.lower() == 'mp4' or ext.lower() == 'avi' or ext.lower() == 'mov': - if file_path.startswith('http'): - raise ValueError("Video files from URLs are not supported. Please download the file and try again.") - - ext = 'jpeg' - video = cv2.VideoCapture(file_path) - # get frames from video - base64Frames = [] - while video.isOpened(): - success, frame = video.read() - if not success: - break - _, buffer = cv2.imencode(".jpg", frame) - base64Frames.append(base64.b64encode(buffer).decode("utf-8")) - video.release() - return base64Frames, ext - else: - raise ValueError(f"File extension {ext} not supported") - - -def encode_image_local(image_path): - ext = image_path.split('.')[-1] - # cast `jpg` to `jpeg` to avoid API issues - if ext.lower() == 'jpg': - ext = 'jpeg' - - assert ext.lower() in ['jpg', 'jpeg', 'png', 'webp'], f"File extension '{ext}' not supported! Available extensions: ['jpg', 'jpeg', 'png', 'webp']" - - with open(image_path, "rb") as image_file: - enc_im = base64.b64encode(image_file.read()).decode('utf-8') - - return [enc_im], ext - - -def encode_image_url(image_url): - ext = image_url.split('.')[-1] - # cast `jpg` to `jpeg` to avoid API issues - if ext.lower() == 'jpg': - ext = 'jpeg' - - assert ext.lower() in ['jpg', 'jpeg', 'png', 'webp'], f"File extension '{ext}' not supported! Available extensions: ['jpg', 'jpeg', 'png', 'webp']" - - enc_im = base64.b64encode(httpx.get(image_url).content).decode("utf-8") - - return [enc_im], ext - - -def ignore_exception(exception=Exception, default=None): - """ Decorator for ignoring exception from a function - e.g. @ignore_exception(DivideByZero) - e.g.2. ignore_exception(DivideByZero)(Divide)(2/0) - """ - def dec(function): - def _dec(*args, **kwargs): - try: - return function(*args, **kwargs) - except exception: - return default - return _dec - return dec - - -def prep_as_str(x): - return f"'{str(x)}'" if ignore_exception()(int)(str(x)) is None else str(x) - - -def deprecated(message): - def deprecated_decorator(func): - def deprecated_func(*args, **kwargs): - warnings.warn("{} is a deprecated function. {}".format(func.__name__, message), - category=DeprecationWarning, - stacklevel=2) - warnings.simplefilter('default', DeprecationWarning) - return func(*args, **kwargs) - return deprecated_func - return deprecated_decorator - - -def toggle_test(enabled: bool = True, default = None): - def test_decorator(func): - def test_func(*args, **kwargs): - if enabled: - return func(*args, **kwargs) - else: - return default - return test_func - return test_decorator - - -class Args: - def __init__(self, skip_none: bool = False, **kwargs): - # for each key set an attribute - for key, value in kwargs.items(): - if value is not None or not skip_none: - if not key.startswith('_'): - setattr(self, key, value) - - -class CustomUserWarning: - def __init__(self, message: str, stacklevel: int = 1, raise_with: Exception | None = None) -> None: - if os.environ.get('SYMAI_WARNINGS', '1') == '1': - caller = inspect.getframeinfo(inspect.stack()[stacklevel][0]) - lineno = caller.lineno - filename = caller.filename - filename = filename[filename.find('symbolicai'):] - with ConsoleStyle('warn') as console: - console.print(f"{filename}:{lineno}: {UserWarning.__name__}: {message}") - # Always raise the warning if raise_with is provided - if raise_with is not None: - raise raise_with(message) - - -# Function to format bytes to a human-readable string -def format_bytes(bytes): - if bytes < 1024: - return f"{bytes} bytes" - elif bytes < 1048576: - return f"{bytes / 1024:.2f} KB" - elif bytes < 1073741824: - return f"{bytes / 1048576:.2f} MB" - else: - return f"{bytes / 1073741824:.2f} GB" - - -@dataclass -class RuntimeInfo: - total_elapsed_time: float - prompt_tokens: int - completion_tokens: int - reasoning_tokens: int - cached_tokens: int - total_calls: int - total_tokens: int - cost_estimate: float - - def __add__(self, other): - add_elapsed_time = other.total_elapsed_time if hasattr(other, "total_elapsed_time") else 0 - add_prompt_tokens = ( - other.prompt_tokens if hasattr(other, "prompt_tokens") else 0 - ) - add_completion_tokens = ( - other.completion_tokens if hasattr(other, "completion_tokens") else 0 - ) - add_total_tokens = other.total_tokens if hasattr(other, "total_tokens") else 0 - add_cost_estimate = ( - other.cost_estimate if hasattr(other, "cost_estimate") else 0 - ) - add_cached_tokens = ( - other.cached_tokens if hasattr(other, "cached_tokens") else 0 - ) - add_reasoning_tokens = ( - other.reasoning_tokens if hasattr(other, "reasoning_tokens") else 0 - ) - add_total_calls = ( - other.total_calls if hasattr(other, "total_calls") else 0 - ) - - return RuntimeInfo( - total_elapsed_time=self.total_elapsed_time + add_elapsed_time, - prompt_tokens=self.prompt_tokens + add_prompt_tokens, - completion_tokens=self.completion_tokens + add_completion_tokens, - reasoning_tokens=self.reasoning_tokens + add_reasoning_tokens, - cached_tokens=self.cached_tokens + add_cached_tokens, - total_calls=self.total_calls + add_total_calls, - total_tokens=self.total_tokens + add_total_tokens, - cost_estimate=self.cost_estimate + add_cost_estimate, - ) - - @staticmethod - def from_tracker(tracker: 'MetadataTracker', total_elapsed_time: float = 0): - if len(tracker.metadata) > 0: - try: - return RuntimeInfo.from_usage_stats(tracker.usage, total_elapsed_time) - except Exception as e: - raise e - CustomUserWarning(f"Failed to parse metadata; returning empty RuntimeInfo: {e}") - return RuntimeInfo(0, 0, 0, 0, 0, 0, 0, 0) - return RuntimeInfo(0, 0, 0, 0, 0, 0, 0, 0) - - @staticmethod - def from_usage_stats(usage_stats: dict | None, total_elapsed_time: float = 0): - if usage_stats is not None: - usage_per_engine = {} - for (engine_name, model_name), data in usage_stats.items(): - data = Box(data) - usage_per_engine[(engine_name, model_name)] = RuntimeInfo( - total_elapsed_time=total_elapsed_time, - prompt_tokens=data.usage.prompt_tokens, - completion_tokens=data.usage.completion_tokens, - reasoning_tokens=getattr(data.usage, 'reasoning_tokens', 0), - cached_tokens=data.prompt_breakdown.cached_tokens, - total_calls=data.usage.total_calls, - total_tokens=data.usage.total_tokens, - cost_estimate=0, # Placeholder for cost estimate - ) - return usage_per_engine - return RuntimeInfo(0, 0, 0, 0, 0, 0, 0, 0) - - @staticmethod - def estimate_cost(info: RuntimeInfo, f_pricing: callable, **kwargs) -> RuntimeInfo: - return RuntimeInfo( - total_elapsed_time=info.total_elapsed_time, - prompt_tokens=info.prompt_tokens, - completion_tokens=info.completion_tokens, - reasoning_tokens=info.reasoning_tokens, - cached_tokens=info.cached_tokens, - total_calls=info.total_calls, - total_tokens=info.total_tokens, - cost_estimate=f_pricing(info, **kwargs), - ) diff --git a/symbolicai-main/symbolicai-main/tests/README.md b/symbolicai-main/symbolicai-main/tests/README.md deleted file mode 100644 index 1e7f8cacb76af8e03f364aa02108ef1b7f077259..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/README.md +++ /dev/null @@ -1,13 +0,0 @@ -You can run the tests with the following command: - -```bash -pytest -``` - -By default, it runs with the `v --ignore=tests/test_imports` flags. - -We recommend to run the `test_imports.py` file separately, as it should be run only once (or occasionally, when you add new imports to the package): - -```bash -pytest -q --tb=no tests/test_imports.py -``` diff --git a/symbolicai-main/symbolicai-main/tests/contract/test_contract.py b/symbolicai-main/symbolicai-main/tests/contract/test_contract.py deleted file mode 100644 index c43881988fc17cbb57899b8e9e46b5c147671a29..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/contract/test_contract.py +++ /dev/null @@ -1,926 +0,0 @@ -import json -import logging -import time -from pathlib import Path -from typing import List, Optional - -import numpy as np -import pytest -from pydantic import Field -from rich.console import Console -from rich.table import Table - -from symai import Expression -from symai.backend.settings import SYMAI_CONFIG -from symai.models import LLMDataModel -from symai.strategy import contract - -NEUROSYMBOLIC = SYMAI_CONFIG.get('NEUROSYMBOLIC_ENGINE_MODEL') - - -class Entity(LLMDataModel): - name: str = Field(description="Name of the entity.") - - def __eq__(self, other): - if not isinstance(other, Entity): - return False - return self.name == other.name - - def __hash__(self): - return hash(self.name) - - -class Relationship(LLMDataModel): - name: str = Field(description="Name of the relationship.") - - def __eq__(self, other): - if not isinstance(other, Relationship): - return False - return self.name == other.name - - def __hash__(self): - return hash(self.name) - - -class Triplet(LLMDataModel): - subject: Entity - predicate: Relationship - object: Entity - confidence: float = Field( - default=1.0, - ge=0.0, - le=1.0, - description="Confidence score for the extracted triplet [0, 1]", - ) - - def __eq__(self, other): - if not isinstance(other, Triplet): - return False - return ( - self.subject == other.subject and - self.predicate == other.predicate and - self.object == other.object - ) - - def __hash__(self): - return hash((hash(self.subject), hash(self.predicate), hash(self.object))) - - -class OntologyClass(LLMDataModel): - name: str = Field(description="Class name in the ontology") - - -class SimpleOntology(LLMDataModel): - classes: List[OntologyClass] = Field(default_factory=list, description="List of classes in the ontology") - - -class KGState(LLMDataModel): - triplets: List[Triplet] = Field(default_factory=list, description="List of triplets.") - - -class TripletExtractorInput(LLMDataModel): - text: str = Field(description="Text to extract triplets from.") - ontology: SimpleOntology = Field(description="Simplified ontology schema for testing.") - state: Optional[KGState] = Field(default=None, description="Existing knowledge graph state (triplets), if any.") - - -class IntermediateAnalysisResult(LLMDataModel): - """A different type that the act method will produce""" - analyzed_text: str = Field(description="Text with analysis markers") - possible_entities: List[str] = Field(default_factory=list, description="Potential entities identified") - possible_relationships: List[str] = Field(default_factory=list, description="Potential relationships identified") - confidence_threshold: float = Field(default=0.7, description="Confidence threshold used") - - -@contract( - pre_remedy=True, - post_remedy=True, - verbose=True, - remedy_retry_params=dict(tries=2, delay=0.1, max_delay=0.5, jitter=0.1, backoff=1.5, graceful=False), -) -class TestTripletExtractor(Expression): - """Test implementation of a TripletExtractor-like class with an act method""" - - def __init__(self, name: str = "test_extractor", threshold: float = 0.7, *args, **kwargs): - super().__init__(*args, **kwargs) - self.name = name - self.threshold = threshold - self._triplets = set() - self.calls_count = 0 - self.analysis_history = [] - - @property - def prompt(self) -> str: - return """ - Extract knowledge triplets from the following text. - A triplet consists of (subject, predicate, object) where: - - subject is an entity - - predicate is a relationship - - object is an entity - - Text: {{text}} - """ - - def pre(self, input: TripletExtractorInput) -> bool: - """Pre-validation: ensure text is not empty and ontology is provided""" - if not input.text or not isinstance(input.text, str): - raise ValueError("Input text must be a non-empty string") - - if not input.ontology or not input.ontology.classes: - raise ValueError("Ontology must be provided with at least one class") - - return True - - def act(self, input: TripletExtractorInput, **kwargs) -> IntermediateAnalysisResult: - """ - Act method that: - 1. Performs preliminary analysis on the text - 2. Identifies potential entities and relationships - 3. Returns an intermediate analysis result (different type than input) - 4. Updates internal state - """ - self.calls_count += 1 - - # Simple entity extraction logic - words = input.text.split() - possible_entities = [] - possible_relationships = [] - - ontology_class_names = [c.name.lower() for c in input.ontology.classes] - - for word in words: - word_lower = word.lower().strip('.,;:!?') - - if word[0].isupper() and len(word) > 1: - possible_entities.append(word) - - for class_name in ontology_class_names: - if class_name in word_lower: - possible_entities.append(word) - - if word_lower in ["is", "has", "contains", "uses", "creates", "performs"]: - possible_relationships.append(word) - - analyzed_text = input.text - for entity in set(possible_entities): - analyzed_text = analyzed_text.replace(entity, f"[ENTITY: {entity}]") - for rel in set(possible_relationships): - analyzed_text = analyzed_text.replace(rel, f"[REL: {rel}]") - - # Test contract state mutation - self.analysis_history.append({ - "call": self.calls_count, - "text": input.text, - "entities_found": len(possible_entities), - "relationships_found": len(possible_relationships) - }) - - return IntermediateAnalysisResult( - analyzed_text=analyzed_text, - possible_entities=possible_entities, - possible_relationships=possible_relationships, - confidence_threshold=self.threshold - ) - - def post(self, output: KGState) -> bool: - """Post-validation: ensure triplets meet confidence threshold""" - if output.triplets is None: - return True # No triplets extracted is a valid state - - for triplet in output.triplets: - if triplet.confidence < self.threshold: - raise ValueError(f"Confidence score {triplet.confidence} is below threshold {self.threshold}!") - - return True - - def forward(self, input: TripletExtractorInput, **kwargs) -> KGState: - if self.contract_result is None: - raise ValueError("Contract failed!") - return self.contract_result - - def extend_triplets(self, new_triplets: List[Triplet]): - """Store extracted triplets""" - if new_triplets: - self._triplets.update(new_triplets) - - def get_triplet_count(self) -> int: - """Return the number of unique triplets extracted""" - return len(self._triplets) - - -# Tests -@pytest.mark.mandatory -def test_triplet_extractor_basic(): - """Test basic functionality of the triplet extractor with act (the happy path!)""" - # Create a simple ontology - ontology = SimpleOntology(classes=[ - OntologyClass(name="Algorithm"), - OntologyClass(name="Model"), - OntologyClass(name="Data") - ]) - - extractor = TestTripletExtractor(threshold=0.7) - - # First call with simple text - input_data = TripletExtractorInput( - text="Neural Networks are models that process data.", - ontology=ontology - ) - - result = extractor(input=input_data) - - # Verify result structure - assert isinstance(result, KGState) - if result.triplets: - for triplet in result.triplets: - assert triplet.confidence >= 0.7 # Respect threshold - - # Verify state was updated - assert extractor.calls_count == 1 - assert len(extractor.analysis_history) == 1 - - -@pytest.mark.mandatory -def test_triplet_extractor_state_persistence(): - """Test that state is maintained across multiple calls""" - ontology = SimpleOntology(classes=[ - OntologyClass(name="Algorithm"), - OntologyClass(name="Model"), - OntologyClass(name="Data") - ]) - - extractor = TestTripletExtractor(threshold=0.7) - - # First call - input_data1 = TripletExtractorInput( - text="Machine Learning models process data.", - ontology=ontology - ) - result1 = extractor(input=input_data1) - - # Store initial triplets - original_triplet_count = extractor.get_triplet_count() - if result1.triplets: - extractor.extend_triplets(result1.triplets) - - # Second call - input_data2 = TripletExtractorInput( - text="Deep Learning is a subtype of Machine Learning.", - ontology=ontology - ) - result2 = extractor(input=input_data2) - - if result2.triplets: - extractor.extend_triplets(result2.triplets) - - # Verify state was maintained - assert extractor.calls_count == 2 - assert len(extractor.analysis_history) == 2 - # Verify triplets accumulate - assert extractor.get_triplet_count() >= original_triplet_count - - -@pytest.mark.mandatory -def test_triplet_extractor_with_multiple_texts(): - """Test processing multiple texts with the same extractor""" - ontology = SimpleOntology(classes=[ - OntologyClass(name="Algorithm"), - OntologyClass(name="Model"), - OntologyClass(name="Data"), - OntologyClass(name="Learning") - ]) - - extractor = TestTripletExtractor(threshold=0.6) # Lower threshold for test - - # List of texts to process - texts = [ - "Neural Networks are models that process data.", - "Machine Learning algorithms improve with more data.", - "Deep Learning is a subset of Machine Learning.", - "GPT models are Transformer-based architectures." - ] - - results = [] - for text in texts: - input_data = TripletExtractorInput( - text=text, - ontology=ontology, - # Pass previous state to demonstrate evolving knowledge - state=results[-1] if results else None - ) - result = extractor(input=input_data) - results.append(result) - - # Extend triplets with each result - if result.triplets: - extractor.extend_triplets(result.triplets) - - # Verify the extractor processed all texts - assert extractor.calls_count == len(texts) - assert len(extractor.analysis_history) == len(texts) - - -@pytest.mark.mandatory -def test_act_transformation(): - """Test that act transforms input to a different type that's used by the LLM""" - ontology = SimpleOntology(classes=[OntologyClass(name="ML")]) - extractor = TestTripletExtractor() - - # Get the act method - act_method = getattr(extractor, 'act') - - # Call act directly to confirm type transformation - input_data = TripletExtractorInput( - text="Neural Networks are ML models.", - ontology=ontology - ) - - # Act should transform TripletExtractorInput to IntermediateAnalysisResult - act_result = act_method(input_data) - - # Verify type transformation - assert isinstance(act_result, IntermediateAnalysisResult) - assert not isinstance(act_result, TripletExtractorInput) - - # Now test through the contract - contract_result = extractor(input=input_data) - - # Result from contract should be KGState - assert isinstance(contract_result, KGState) - - -@pytest.mark.mandatory -def test_act_signature_validation(): - """Test that contract properly validates act method signature""" - - @contract() # Basic contract decorator for testing - class BadActSignatureMissingInput(Expression): - @property - def prompt(self) -> str: return "test" - def act(self, wrong_name: TripletExtractorInput, **kwargs) -> IntermediateAnalysisResult: - return IntermediateAnalysisResult(analyzed_text=wrong_name.text) - def forward(self, **kwargs) -> KGState: # Make forward more lenient for this test - return KGState() - - @contract() - class BadActSignatureNoAnnotation(Expression): - @property - def prompt(self) -> str: return "test" - def act(self, input, **kwargs) -> IntermediateAnalysisResult: # No type annotation for input - return IntermediateAnalysisResult(analyzed_text=input.text) - def forward(self, **kwargs) -> KGState: - return KGState() - - @contract() - class BadActSignatureNoReturnAnnotation(Expression): - @property - def prompt(self) -> str: return "test" - def act(self, input: TripletExtractorInput, **kwargs): # No return type annotation - return IntermediateAnalysisResult(analyzed_text=input.text) - def forward(self, **kwargs) -> KGState: - return KGState() - - @contract() - class BadActSignatureWrongInputType(Expression): - @property - def prompt(self) -> str: return "test" - def act(self, input: str, **kwargs) -> IntermediateAnalysisResult: # Input not LLMDataModel - return IntermediateAnalysisResult(analyzed_text=input) - def forward(self, **kwargs) -> KGState: - return KGState() - - @contract() - class BadActSignatureWrongReturnType(Expression): - @property - def prompt(self) -> str: return "test" - def act(self, input: TripletExtractorInput, **kwargs) -> str: # Return not LLMDataModel - return input.text - def forward(self, **kwargs) -> KGState: - return KGState() - - dummy_ontology = SimpleOntology(classes=[OntologyClass(name="Test")]) - dummy_input = TripletExtractorInput(text="test", ontology=dummy_ontology) - - # The contract decorator's _act method will raise TypeError internally. - # This TypeError will be caught by wrapped_forward, contract_successful will be False. - # The lenient forward methods will then be called. - - contract_bsmi = BadActSignatureMissingInput() - contract_bsmi(input=dummy_input) - assert not contract_bsmi.contract_successful # Check that the contract failed - - contract_bsna = BadActSignatureNoAnnotation() - contract_bsna(input=dummy_input) - assert not contract_bsna.contract_successful - - contract_bsnra = BadActSignatureNoReturnAnnotation() - contract_bsnra(input=dummy_input) - assert not contract_bsnra.contract_successful - - contract_bswit = BadActSignatureWrongInputType() - contract_bswit(input=dummy_input) - assert not contract_bswit.contract_successful - - contract_bswrt = BadActSignatureWrongReturnType() - contract_bswrt(input=dummy_input) - assert not contract_bswrt.contract_successful - - -@pytest.mark.mandatory -def test_act_contract_flow(): - """Test how act affects the contract's execution flow""" - - @contract(pre_remedy=True, post_remedy=True, verbose=True) - class FlowTestContractPrecise(Expression): - def __init__(self): - super().__init__() - self.flow_log = [] - @property - def prompt(self) -> str: - self.flow_log.append("prompt_accessed") - return "test prompt for flow" - def pre(self, input: TripletExtractorInput) -> bool: - self.flow_log.append("pre_called") - return True - def act(self, input: TripletExtractorInput, **kwargs) -> IntermediateAnalysisResult: - self.flow_log.append("act_called") - return IntermediateAnalysisResult(analyzed_text=input.text, confidence_threshold=0.7) - def post(self, output: KGState) -> bool: - self.flow_log.append("post_called") - # output is the KGState instance created by _validate_output based on LLM response - # For this flow test, we just care it's called. - return True - def forward(self, input: TripletExtractorInput, **kwargs) -> KGState: - self.flow_log.append("original_forward_called") - if self.contract_result is None: - # This indicates contract failed before _validate_output set contract_result, - # or _validate_output itself failed to produce a valid result. - # For a successful flow, contract_result should be set. - # If testing failure flow, this path might be taken. - # For this happy path flow test, contract_result should be valid. - raise ValueError("Contract failed, contract_result is None in original_forward!") - return self.contract_result - - test_contract_instance_precise = FlowTestContractPrecise() - dummy_ontology = SimpleOntology(classes=[OntologyClass(name="Test")]) - dummy_input_data = TripletExtractorInput(text="flow test text", ontology=dummy_ontology) - - # In a real scenario with pre_remedy=True and post_remedy=True, - # _validate_input and _validate_output in strategy.py would use the prompt. - # _validate_output would create/validate the KGState (final output type) using an LLM call. - # This KGState then becomes self.contract_result. - # The user's `post` is called by `_validate_output` with this KGState. - # The user's `forward` is called by `wrapped_forward` and should return `self.contract_result`. - - # We are not mocking LLM calls here, so the actual KGState might be empty or default. - # The important part is the sequence of method calls. - result = test_contract_instance_precise(input=dummy_input_data) - - # Expected order: - # 1. prompt_accessed (by _validate_input due to pre_remedy=True) - # 2. pre_called (by _validate_input) - # 3. act_called (by _act) - # 4. prompt_accessed (by _validate_output due to post_remedy=True, assuming it uses prompt) - # 5. post_called (by _validate_output) - # 6. original_forward_called (by wrapped_forward in finally block) - - # Check the sequence - assert "pre_called" in test_contract_instance_precise.flow_log - assert "act_called" in test_contract_instance_precise.flow_log - assert "post_called" in test_contract_instance_precise.flow_log - assert "original_forward_called" in test_contract_instance_precise.flow_log - - # Check relative order - assert test_contract_instance_precise.flow_log.index("pre_called") < \ - test_contract_instance_precise.flow_log.index("act_called") - - # Note: 'post_called' is called within _validate_output. Prompt access by _validate_output - # might happen before or after calling 'post', depending on _validate_output's internal logic. - # For this test, we simplify and just check act before post. - assert test_contract_instance_precise.flow_log.index("act_called") < \ - test_contract_instance_precise.flow_log.index("post_called") - - assert test_contract_instance_precise.flow_log.index("post_called") < \ - test_contract_instance_precise.flow_log.index("original_forward_called") - - # Verify prompt access. Exact number of calls depends on strategy.py internal logic. - assert test_contract_instance_precise.flow_log.count("prompt_accessed") >= 1 - - -@pytest.mark.mandatory -def test_act_contract_state_interaction(): - """Test how act's state changes affect contract validation and error handling""" - - @contract(pre_remedy=True, post_remedy=True, verbose=True) - class StateInteractionContract(Expression): - def __init__(self): - super().__init__() - self.custom_threshold = 0.5 # Initial state - self.prompt_access_count = 0 - - @property - def prompt(self) -> str: - self.prompt_access_count += 1 - return "Analyze sentiment of: {{text}}" - - def pre(self, input: TripletExtractorInput) -> bool: - if input.text == "fail_pre_with_remedy": # This will trigger remedy - raise ValueError("Pre-condition failed by 'fail_pre_with_remedy'") - return True - - def act(self, input: TripletExtractorInput, **kwargs) -> IntermediateAnalysisResult: - if input.text == "fail_act": - raise RuntimeError("Simulated failure in act method") - # Modify instance state that might be used in post - self.custom_threshold = 0.9 - return IntermediateAnalysisResult( - analyzed_text=f"{input.text} - analyzed", - confidence_threshold=self.custom_threshold # Pass it along - ) - - def post(self, output: KGState) -> bool: - # Post-condition uses the updated threshold from act - if output.triplets: - for triplet in output.triplets: - if triplet.confidence < self.custom_threshold: - raise ValueError(f"Post-condition failed: Confidence {triplet.confidence} < {self.custom_threshold}") - return True - - def forward(self, input: TripletExtractorInput, **kwargs) -> KGState: - # This is the original_forward method. - if not self.contract_successful and self.contract_result is None: # Fallback path - return KGState(triplets=[Triplet(subject=Entity(name="Fallback"), - predicate=Relationship(name="created_due_to_failure"), - object=Entity(name=input.text[:10]), # Use original input for fallback - confidence=0.1)]) - - if self.contract_result is None: # Should ideally not happen if contract_successful - raise ValueError("Contract successful but contract_result is None in forward!") - - return self.contract_result - - contract_instance = StateInteractionContract() - dummy_ontology = SimpleOntology(classes=[OntologyClass(name="Test")]) - - # Case 1: Act modifies state, post uses it, and validation passes. - # For this to pass, _validate_output (which calls post) must be "aware" of an LLM producing - # a KGState with triplets that meet the new threshold of 0.9. - # Without a mock LLM, we assume _validate_output can produce such a result if prompted correctly. - input_data_pass = TripletExtractorInput( - text="Test_Pass_State_Interaction", - ontology=dummy_ontology, - # Simulate an incoming state that, if returned by LLM, would pass the post-condition - state=KGState(triplets=[Triplet(subject=Entity(name="S"), predicate=Relationship(name="P"), object=Entity(name="O"), confidence=0.95)]) - ) - # We rely on the actual contract mechanisms. If the LLM happens to return - # triplets like those in `input_data_pass.state` (or an empty list), it might pass. - # This test is more of an integration style for state due to LLM dependency. - # For a more controlled unit test, one might need to mock the LLM response within _validate_output. - try: - # This call will use the real _validate_output, which involves LLM. - # If LLM produces triplets, they must meet the 0.9 threshold set by act. - # If LLM produces no triplets, post will pass. - result_pass = contract_instance(input=input_data_pass) - assert contract_instance.custom_threshold == 0.9 # Verify act updated state - if result_pass.triplets: # If any triplets were produced by the LLM - for t in result_pass.triplets: - assert t.confidence >= 0.9 - except Exception as e: - # Allow LLM errors or validation failures if LLM doesn't cooperate for "pass" case - logging.warning(f"State interaction pass test encountered: {e}. This might be due to LLM variability.") - pass - - - # Case 2: Act itself fails - contract_instance_fail_act = StateInteractionContract() # Re-initialize for a clean state - input_data_fail_act = TripletExtractorInput(text="fail_act", ontology=dummy_ontology) - - # The RuntimeError from `act` will be caught by `wrapped_forward`. - # `contract_successful` will be False. - # The `finally` block in `wrapped_forward` will call `original_forward` (StateInteractionContract.forward). - # StateInteractionContract.forward will execute its fallback logic. - - fallback_result_from_act_failure = contract_instance_fail_act(input=input_data_fail_act) - - # Verify fallback output - assert fallback_result_from_act_failure.triplets[0].subject.name == "Fallback" - assert fallback_result_from_act_failure.triplets[0].object.name == "fail_act"[:10] # Original input text used in fallback - - # After the error in `act`, check state that should not have been changed by the aborted `act` call. - # In StateInteractionContract, `act` raises RuntimeError BEFORE `self.custom_threshold` is changed from 0.5 to 0.9. - assert contract_instance_fail_act.custom_threshold == 0.5 - - # Verify contract_successful is False - assert not contract_instance_fail_act.contract_successful - - # Reset state for next test part - contract_instance.custom_threshold = 0.5 - contract_instance.contract_successful = False # Reset for clarity - contract_instance.contract_result = None - - - # Case 3: Pre-condition fails (with pre_remedy=True), test fallback if remedy fails. - @contract(pre_remedy=False, post_remedy=False, verbose=True) - class StateInteractionNoRemedyPreFail(Expression): - def __init__(self): super().__init__() - @property - def prompt(self) -> str: return "test" # Not used with remedy=False - def pre(self, input: TripletExtractorInput) -> bool: - if input.text == "fail_pre_direct": - # With pre_remedy=False, returning False or raising will cause _validate_input to raise. - raise ValueError("Direct pre fail") - return True - # Define act and post to satisfy contract requirements, though not central to this test part - def act(self, input: TripletExtractorInput, **kwargs) -> IntermediateAnalysisResult: - return IntermediateAnalysisResult(analyzed_text=input.text) - def post(self, output: KGState) -> bool: - return True - def forward(self, input: TripletExtractorInput, **kwargs) -> KGState: # input here is original_input - if not self.contract_successful and self.contract_result is None: # Fallback - return KGState(triplets=[Triplet(subject=Entity(name="FallbackDirectPreFail"), - predicate=Relationship(name="P"), - object=Entity(name=input.text[:10]), - confidence=0.1)]) - # This path should not be taken if pre-failed and fallback occurred. - if self.contract_result is None: raise ValueError("Contract result none in forward for success path"); - return self.contract_result - - contract_no_remedy_pre = StateInteractionNoRemedyPreFail() - input_fail_pre_direct = TripletExtractorInput(text="fail_pre_direct", ontology=dummy_ontology) - - # `_validate_input` (with pre_remedy=False) will raise Exception if pre returns False/raises. - # This exception is caught by `wrapped_forward`, `contract_successful` becomes False. - # `original_forward` (StateInteractionNoRemedyPreFail.forward) is called with original_input. - fallback_pre_direct_fail = contract_no_remedy_pre(input=input_fail_pre_direct) - assert fallback_pre_direct_fail.triplets[0].subject.name == "FallbackDirectPreFail" - assert fallback_pre_direct_fail.triplets[0].object.name == "fail_pre_d" # original input text - assert not contract_no_remedy_pre.contract_successful - - -@pytest.mark.mandatory -def test_contract_result_propagation(): - """Test that contract_result is properly set by _validate_output and used by forward""" - - @contract(pre_remedy=False, post_remedy=True, verbose=True) # post_remedy=True will use LLM - class ResultPropagationContract(Expression): - def __init__(self): - super().__init__() - self.intermediate_text_from_act = None - - @property - def prompt(self) -> str: - # This prompt will be used by _validate_output - # It should demonstrate using the output of the 'act' method. - # The `current_input` to _validate_output in strategy.py IS the output of `_act`. - # So, if act returns IntermediateAnalysisResult, then {{analyzed_text}} should be available. - return "Create KGState based on analyzed text: {{analyzed_text}}. Entities: {{possible_entities}}. Relationships: {{possible_relationships}}." - - def pre(self, input: TripletExtractorInput) -> bool: return True - - def act(self, input: TripletExtractorInput, **kwargs) -> IntermediateAnalysisResult: - self.intermediate_text_from_act = f"act_on_{input.text}" - return IntermediateAnalysisResult( - analyzed_text=self.intermediate_text_from_act, - possible_entities=["entity_from_act"], - possible_relationships=["rel_from_act"], - confidence_threshold=0.88 - ) - - def post(self, output: KGState) -> bool: - # This post validates the KGState produced by the LLM in _validate_output. - # Check if the KGState somehow reflects the data from IntermediateAnalysisResult. - # This depends on how well the LLM uses the prompt. - if output.triplets: - for triplet in output.triplets: - if self.intermediate_text_from_act and self.intermediate_text_from_act[:5] in triplet.subject.name: - logging.info(f"Post-validation: Found data from 'act' in triplet: {triplet.subject.name}") - return True # Found evidence of act's output influencing the result - # If no triplet contains evidence, it might still be a pass if LLM chose not to include it. - # For a robust test, prompt might need to be more directive. - return True # Default pass if no specific check fails - - def forward(self, input: TripletExtractorInput, **kwargs) -> KGState: - if not self.contract_successful and self.contract_result is None: # Fallback - return KGState(triplets=[Triplet(subject=Entity(name="FallbackForwardProp"), predicate=Relationship(name="P"), object=Entity(name="O"), confidence=0.1)]) - - if self.contract_result is None: - raise ValueError("Contract.contract_result was None in forward (success path)!") - - assert isinstance(self.contract_result, KGState) - return self.contract_result - - contract_instance = ResultPropagationContract() - dummy_ontology = SimpleOntology(classes=[OntologyClass(name="Test")]) # Not used by this contract's prompt directly - input_data = TripletExtractorInput(text="propagate_test_text", ontology=dummy_ontology) - - # This call will use the real _validate_output, which involves an LLM call - # using the prompt defined in ResultPropagationContract. - # The prompt will be formatted with data from the IntermediateAnalysisResult returned by `act`. - result = contract_instance(input=input_data) - - assert isinstance(result, KGState) - assert contract_instance.contract_successful # Check that the main path was successful - - # We can't easily assert specific content of `result.triplets` without a mock LLM, - # as it depends on the real LLM's interpretation of the prompt. - # However, if `post_remedy=True` and `post` passes, and `verbose=True` in contract, - # logs would show the LLM call and the data flow. - # The `post` method above includes a log if it finds evidence. - logging.info(f"Resulting KG for propagation test: {result.model_dump_json(indent=2)}") - - if result.triplets and contract_instance.intermediate_text_from_act: - found_evidence = any(contract_instance.intermediate_text_from_act[:5] in t.subject.name for t in result.triplets) - logging.info(f"Evidence of 'act' data in final result: {found_evidence}") - - -@pytest.mark.mandatory -def test_contract_perf_stats(): - """Test the contract_perf_stats method correctly tracks and reports timing statistics.""" - - class PerfStatsInput(LLMDataModel): - text: str = Field(description="Input text for performance testing") - - class PerfStatsOutput(LLMDataModel): - processed_text: str = Field(description="Processed text output") - - @contract(pre_remedy=True, post_remedy=True, verbose=True) - class PerfStatsTestContract(Expression): - def __init__(self): - super().__init__() - self.sleep_time = 0.01 # Default sleep time in seconds - - @property - def prompt(self) -> str: - return "performance stats test prompt" - - def pre(self, input: PerfStatsInput) -> bool: - time.sleep(self.sleep_time + 1) - return True - - def act(self, input: PerfStatsInput, **kwargs) -> PerfStatsOutput: - time.sleep(self.sleep_time + 2) - return PerfStatsOutput(processed_text=f"Processed: {input.text}") - - def post(self, output: PerfStatsOutput) -> bool: - time.sleep(self.sleep_time + 3) - return True - - def forward(self, input: PerfStatsInput, **kwargs) -> PerfStatsOutput: - time.sleep(self.sleep_time + 1) - return self.contract_result if self.contract_result else PerfStatsOutput(processed_text=f"Original: {input.text}") - - contract_instance = PerfStatsTestContract() - - input_texts = ["test1", "test2", "test3"] - sleep_times = [0.01, 0.02, 0.03] - - for i, (input_text, sleep_time) in enumerate(zip(input_texts, sleep_times)): - contract_instance.sleep_time = sleep_time - input_model = PerfStatsInput(text=input_text) - result = contract_instance(input=input_model) - assert isinstance(result, PerfStatsOutput) - assert result.processed_text, "Processed text should not be empty" - - stats = contract_instance.contract_perf_stats() - - expected_operations = [ - "input_validation", - "act_execution", - "output_validation", - "forward_execution", - "contract_execution" - ] - - for op in expected_operations: - assert op in stats, f"Operation {op} missing from stats" - - assert "overhead" in stats, f"Overhead tracking missing from stats" - - assert stats["act_execution"]["count"] == 3 - - for op in ["act_execution", "contract_execution"]: - if stats[op]["count"] > 1: - assert stats[op]["min"] <= stats[op]["mean"] <= stats[op]["max"], f"Statistics for {op} are inconsistent" - - for op in expected_operations: - if stats[op]["count"] > 0: - if stats[op]["count"] > 1: - assert stats[op]["min"] <= stats[op]["mean"] <= stats[op]["max"], f"Statistics for {op} are inconsistent" - - assert stats[op]["total"] >= 0 - assert stats[op]["mean"] >= 0 - assert stats[op]["min"] >= 0 - assert stats[op]["max"] >= 0 - assert stats[op]["std"] >= 0 - - if stats["contract_execution"]["total"] > 0: - tracked_ops = expected_operations[:-1] # Exclude contract_execution - total_percentage = sum(stats[op]["percentage"] for op in tracked_ops) + stats["overhead"]["percentage"] - # Should be very close to 100% - assert abs(total_percentage - 100.0) < 0.1, "Percentages including overhead should sum to 100%" - - # Verify overhead calculation - tracked_time = sum(stats[op]["total"] for op in tracked_ops) - total_time = stats["contract_execution"]["total"] - calculated_overhead = total_time - tracked_time - assert abs(calculated_overhead - stats["overhead"]["total"]) < 0.001, "Overhead calculation is incorrect" - - -@pytest.mark.mandatory -def test_act_state_modification_without_input_change(): - class StateModificationInput(LLMDataModel): - value: str = Field(description="Input value") - - class StateModificationOutput(LLMDataModel): - value: str = Field(description="Output value") - - @contract(pre_remedy=True, post_remedy=True, verbose=True) - class StateModificationContract(Expression): - def __init__(self): - super().__init__() - self.state_counter = 0 - self.last_input_value = None - self.method_calls = [] - - @property - def prompt(self) -> str: - self.method_calls.append("prompt_accessed") - return "Test contract that modifies state without changing input" - - def pre(self, input: StateModificationInput) -> bool: - self.method_calls.append("pre_called") - return True - - def act(self, input: StateModificationInput, **kwargs) -> StateModificationInput: - self.method_calls.append("act_called") - # Modify internal state - self.state_counter += 1 - self.last_input_value = input.value - - # Store the input object's identity to verify it's the same object throughout - self.original_input_id = id(input) - - # Return the input unchanged - this tests that we don't need - # to create a new object when we just want to modify state - return input - - def post(self, output: StateModificationOutput) -> bool: - self.method_calls.append("post_called") - return True - - def forward(self, input: StateModificationInput, **kwargs) -> StateModificationOutput: - self.method_calls.append("forward_called") - # Verify that the input received in forward is the same object that went through act - # This confirms proper input propagation through the contract mechanism - self.input_preserved = (id(input) == self.original_input_id) - - # In a successful contract flow, contract_result should be set - # For this test, we want to use the validated input but create our own output - return StateModificationOutput(value=input.value) - - # Create test input - test_input = StateModificationInput(value="test_value") - - # Create contract instance - contract_instance = StateModificationContract() - - # Initial state should be zero - assert contract_instance.state_counter == 0 - assert contract_instance.last_input_value is None - - # Call the contract - result = contract_instance(input=test_input) - - # Verify the execution flow - assert "pre_called" in contract_instance.method_calls - assert "act_called" in contract_instance.method_calls - assert "post_called" in contract_instance.method_calls - assert "forward_called" in contract_instance.method_calls - - # Check the correct ordering of method calls - assert contract_instance.method_calls.index("pre_called") < contract_instance.method_calls.index("act_called") - assert contract_instance.method_calls.index("act_called") < contract_instance.method_calls.index("post_called") - assert contract_instance.method_calls.index("post_called") < contract_instance.method_calls.index("forward_called") - - # Verify that the state was modified by the act method - assert contract_instance.state_counter == 1 - assert contract_instance.last_input_value == "test_value" - - # Verify that the input object was preserved throughout the contract execution - # This is a key test for our refactored _act method, ensuring it properly - # propagates the exact same input object without creating new instances - assert contract_instance.input_preserved, "Input object identity was not preserved through the contract flow" - - # Verify that the output has the expected value - assert isinstance(result, StateModificationOutput) - assert result.value == "test_value" - - # Call the contract again to verify state accumulation - result = contract_instance(input=test_input) - - # State counter should have been incremented again - assert contract_instance.state_counter == 2 - - -if __name__ == "__main__": - pytest.main() diff --git a/symbolicai-main/symbolicai-main/tests/data/pg1727.txt b/symbolicai-main/symbolicai-main/tests/data/pg1727.txt deleted file mode 100644 index 2d13ec2b74169fb2cb4ed23c8c0f53fe1ac9ba00..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/data/pg1727.txt +++ /dev/null @@ -1,12242 +0,0 @@ -The Project Gutenberg eBook of The Odyssey - -This ebook is for the use of anyone anywhere in the United States and -most other parts of the world at no cost and with almost no restrictions -whatsoever. You may copy it, give it away or re-use it under the terms -of the Project Gutenberg License included with this ebook or online -at www.gutenberg.org. If you are not located in the United States, -you will have to check the laws of the country where you are located -before using this eBook. - -Title: The Odyssey - -Author: Homer - -Translator: Samuel Butler - -Release date: April 1, 1999 [eBook #1727] - Most recently updated: December 2, 2023 - -Language: English - -Credits: Jim Tinsley and David Widger - - -*** START OF THE PROJECT GUTENBERG EBOOK THE ODYSSEY *** - - - - -[Illustration] - - - - -The Odyssey - -by Homer - -rendered into English prose for the use of those who cannot read the -original - -Contents - - PREFACE TO FIRST EDITION - PREFACE TO SECOND EDITION - THE ODYSSEY - BOOK I. - BOOK II. - BOOK III. - BOOK IV. - BOOK V. - BOOK VI. - BOOK VII. - BOOK VIII. - BOOK IX. - BOOK X. - BOOK XI. - BOOK XII. - BOOK XIII. - BOOK XIV. - BOOK XV. - BOOK XVI. - BOOK XVII. - BOOK XVIII. - BOOK XIX. - BOOK XX. - BOOK XXI. - BOOK XXII. - BOOK XXIII. - BOOK XXIV. - FOOTNOTES: - - -AL PROFESSORE -CAV. BIAGIO INGROIA, -PREZIOSO ALLEATO -L’AUTORE RICONOSCENTE. - - - - -PREFACE TO FIRST EDITION - - -This translation is intended to supplement a work entitled “The -Authoress of the Odyssey”, which I published in 1897. I could not give -the whole “Odyssey” in that book without making it unwieldy, I -therefore epitomised my translation, which was already completed and -which I now publish in full. - -I shall not here argue the two main points dealt with in the work just -mentioned; I have nothing either to add to, or to withdraw from, what I -have there written. The points in question are: - -(1) that the “Odyssey” was written entirely at, and drawn entirely -from, the place now called Trapani on the West Coast of Sicily, alike -as regards the Phaeacian and the Ithaca scenes; while the voyages of -Ulysses, when once he is within easy reach of Sicily, solve themselves -into a periplus of the island, practically from Trapani back to -Trapani, via the Lipari islands, the Straits of Messina, and the island -of Pantellaria. - -(2) That the poem was entirely written by a very young woman, who lived -at the place now called Trapani, and introduced herself into her work -under the name of Nausicaa. - -The main arguments on which I base the first of these somewhat -startling contentions, have been prominently and repeatedly before the -English and Italian public ever since they appeared (without rejoinder) -in the “Athenaeum” for January 30 and February 20, 1892. Both -contentions were urged (also without rejoinder) in the Johnian “Eagle” -for the Lent and October terms of the same year. Nothing to which I -should reply has reached me from any quarter, and knowing how anxiously -I have endeavoured to learn the existence of any flaws in my argument, -I begin to feel some confidence that, did such flaws exist, I should -have heard, at any rate about some of them, before now. Without, -therefore, for a moment pretending to think that scholars generally -acquiesce in my conclusions, I shall act as thinking them little likely -so to gainsay me as that it will be incumbent upon me to reply, and -shall confine myself to translating the “Odyssey” for English readers, -with such notes as I think will be found useful. Among these I would -especially call attention to one on xxii. 465-473 which Lord Grimthorpe -has kindly allowed me to make public. - -I have repeated several of the illustrations used in “The Authoress of -the Odyssey”, and have added two which I hope may bring the outer court -of Ulysses’ house more vividly before the reader. I should like to -explain that the presence of a man and a dog in one illustration is -accidental, and was not observed by me till I developed the negative. -In an appendix I have also reprinted the paragraphs explanatory of the -plan of Ulysses’ house, together with the plan itself. The reader is -recommended to study this plan with some attention. - -In the preface to my translation of the “Iliad” I have given my views -as to the main principles by which a translator should be guided, and -need not repeat them here, beyond pointing out that the initial liberty -of translating poetry into prose involves the continual taking of more -or less liberty throughout the translation; for much that is right in -poetry is wrong in prose, and the exigencies of readable prose are the -first things to be considered in a prose translation. That the reader, -however, may see how far I have departed from strict construe, I will -print here Messrs. Butcher and Lang’s translation of the sixty lines or -so of the “Odyssey.” Their translation runs: - -Tell me, Muse, of that man, so ready at need, who wandered far and -wide, after he had sacked the sacred citadel of Troy, and many were the -men whose towns he saw and whose mind he learnt, yea, and many the woes -he suffered in his heart on the deep, striving to win his own life and -the return of his company. Nay, but even so he saved not his company, -though he desired it sore. For through the blindness of their own -hearts they perished, fools, who devoured the oxen of Helios Hyperion: -but the god took from them their day of returning. Of these things, -goddess, daughter of Zeus, whencesoever thou hast heard thereof, -declare thou even unto us. - - Now all the rest, as many as fled from sheer destruction, were at - home, and had escaped both war and sea, but Odysseus only, craving - for his wife and for his homeward path, the lady nymph Calypso - held, that fair goddess, in her hollow caves, longing to have him - for her lord. But when now the year had come in the courses of the - seasons, wherein the gods had ordained that he should return home - to Ithaca, not even there was he quit of labours, not even among - his own; but all the gods had pity on him save Poseidon, who raged - continually against godlike Odysseus, till he came to his own - country. Howbeit Poseidon had now departed for the distant - Ethiopians, the Ethiopians that are sundered in twain, the - uttermost of men, abiding some where Hyperion sinks and some where - he rises. There he looked to receive his hecatomb of bulls and - rams, there he made merry sitting at the feast, but the other gods - were gathered in the halls of Olympian Zeus. Then among them the - father of men and gods began to speak, for he bethought him in his - heart of noble Aegisthus, whom the son of Agamemnon, far-famed - Orestes, slew. Thinking upon him he spake out among the Immortals: - ‘Lo you now, how vainly mortal men do blame the gods! For of us - they say comes evil, whereas they even of themselves, through the - blindness of their own hearts, have sorrows beyond that which is - ordained. Even as of late Aegisthus, beyond that which was - ordained, took to him the wedded wife of the son of Atreus, and - killed her lord on his return, and that with sheer doom before his - eyes, since we had warned him by the embassy of Hermes the - keen-sighted, the slayer of Argos, that he should neither kill the - man, nor woo his wife. For the son of Atreus shall be avenged at - the hand of Orestes, so soon as he shall come to man’s estate and - long for his own country. So spake Hermes, yet he prevailed not on - the heart of Aegisthus, for all his good will; but now hath he paid - one price for all.’ - - And the goddess, grey-eyed Athene, answered him, saying: ‘O father, - our father Cronides, throned in the highest; that man assuredly - lies in a death that is his due; so perish likewise all who work - such deeds! But my heart is rent for wise Odysseus, the hapless - one, who far from his friends this long while suffereth affliction - in a sea-girt isle, where is the navel of the sea, a woodland isle, - and therein a goddess hath her habitation, the daughter of the - wizard Atlas, who knows the depths of every sea, and himself - upholds the tall pillars which keep earth and sky asunder. His - daughter it is that holds the hapless man in sorrow: and ever with - soft and guileful tales she is wooing him to forgetfulness of - Ithaca. But Odysseus yearning to see if it were but the smoke leap - upwards from his own land, hath a desire to die. As for thee, thine - heart regardeth it not at all, Olympian! What! Did not Odysseus by - the ships of the Argives make thee free offering of sacrifice in - the wide Trojan land? Wherefore wast thou then so wroth with him, O - Zeus?’ - - -The “Odyssey” (as every one knows) abounds in passages borrowed from -the “Iliad”; I had wished to print these in a slightly different type, -with marginal references to the “Iliad,” and had marked them to this -end in my MS. I found, however, that the translation would be thus -hopelessly scholasticised, and abandoned my intention. I would -nevertheless urge on those who have the management of our University -presses, that they would render a great service to students if they -would publish a Greek text of the “Odyssey” with the Iliadic passages -printed in a different type, and with marginal references. I have given -the British Museum a copy of the “Odyssey” with the Iliadic passages -underlined and referred to in MS.; I have also given an “Iliad” marked -with all the Odyssean passages, and their references; but copies of -both the “Iliad” and “Odyssey” so marked ought to be within easy reach -of all students. - -Any one who at the present day discusses the questions that have arisen -round the “Iliad” since Wolf’s time, without keeping it well before his -reader’s mind that the “Odyssey” was demonstrably written from one -single neighbourhood, and hence (even though nothing else pointed to -this conclusion) presumably by one person only—that it was written -certainly before 750, and in all probability before 1000 B.C.—that the -writer of this very early poem was demonstrably familiar with the -“Iliad” as we now have it, borrowing as freely from those books whose -genuineness has been most impugned, as from those which are admitted to -be by Homer—any one who fails to keep these points before his readers, -is hardly dealing equitably by them. Any one on the other hand, who -will mark his “Iliad” and his “Odyssey” from the copies in the British -Museum above referred to, and who will draw the only inference that -common sense can draw from the presence of so many identical passages -in both poems, will, I believe, find no difficulty in assigning their -proper value to a large number of books here and on the Continent that -at present enjoy considerable reputations. Furthermore, and this -perhaps is an advantage better worth securing, he will find that many -puzzles of the “Odyssey” cease to puzzle him on the discovery that they -arise from over-saturation with the “Iliad.” - -Other difficulties will also disappear as soon as the development of -the poem in the writer’s mind is understood. I have dealt with this at -some length in pp. 251-261 of “The Authoress of the Odyssey”. Briefly, -the “Odyssey” consists of two distinct poems: (1) The Return of -Ulysses, which alone the Muse is asked to sing in the opening lines of -the poem. This poem includes the Phaeacian episode, and the account of -Ulysses’ adventures as told by himself in Books ix.-xii. It consists of -lines 1-79 (roughly) of Book i., of line 28 of Book v., and thence -without intermission to the middle of line 187 of Book xiii., at which -point the original scheme was abandoned. - -(2) The story of Penelope and the suitors, with the episode of -Telemachus’ voyage to Pylos. This poem begins with line 80 (roughly) of -Book i., is continued to the end of Book iv., and not resumed till -Ulysses wakes in the middle of line 187, Book xiii., from whence it -continues to the end of Book xxiv. - -In “The Authoress of the Odyssey”, I wrote: - -the introduction of lines xi., 115-137 and of line ix., 535, with the -writing a new council of the gods at the beginning of Book v., to take -the place of the one that was removed to Book i., 1-79, were the only -things that were done to give even a semblance of unity to the old -scheme and the new, and to conceal the fact that the Muse, after being -asked to sing of one subject, spend two-thirds of her time in singing a -very different one, with a climax for which no-one has asked her. For -roughly the Return occupies eight Books, and Penelope and the Suitors -sixteen. - - -I believe this to be substantially correct. - -Lastly, to deal with a very unimportant point, I observe that the -Leipsic Teubner edition of 894 makes Books ii. and iii. end with a -comma. Stops are things of such far more recent date than the -“Odyssey,” that there does not seem much use in adhering to the text in -so small a matter; still, from a spirit of mere conservatism, I have -preferred to do so. Why [Greek] at the beginnings of Books ii. and -viii., and [Greek], at the beginning of Book vii. should have initial -capitals in an edition far too careful to admit a supposition of -inadvertence, when [Greek] at the beginning of Books vi. and xiii., and -[Greek] at the beginning of Book xvii. have no initial capitals, I -cannot determine. No other Books of the “Odyssey” have initial capitals -except the three mentioned unless the first word of the Book is a -proper name. - -S. BUTLER. - - -_July_ 25, 1900. - - - - -PREFACE TO SECOND EDITION - - -Butler’s Translation of the “Odyssey” appeared originally in 1900, and -The Authoress of the Odyssey in 1897. In the preface to the new edition -of “The Authoress”, which is published simultaneously with this new -edition of the Translation, I have given some account of the genesis of -the two books. - -The size of the original page has been reduced so as to make both books -uniform with Butler’s other works; and, fortunately, it has been -possible, by using a smaller type, to get the same number of words into -each page, so that the references remain good, and, with the exception -of a few minor alterations and rearrangements now to be enumerated so -far as they affect the Translation, the new editions are faithful -reprints of the original editions, with misprints and obvious errors -corrected—no attempt having been made to edit them or to bring them up -to date. - -(a) The Index has been revised. - -(b) Owing to the reduction in the size of the page it has been -necessary to shorten some of the headlines, and here advantage has been -taken of various corrections of and additions to the headlines and -shoulder-notes made by Butler in his own copies of the two books. - -(c) For the most part each of the illustrations now occupies a page, -whereas in the original editions they generally appeared two on the -page. It has been necessary to reduce the plan of the House of Ulysses. - -On page 153 of “The Authoress” Butler says: “No great poet would -compare his hero to a paunch full of blood and fat, cooking before the -fire (xx, 24-28).” This passage is not given in the abridged Story of -the “Odyssey” at the beginning of the book, but in the Translation it -occurs in these words: - -“Thus he chided with his heart, and checked it into endurance, but he -tossed about as one who turns a paunch full of blood and fat in front -of a hot fire, doing it first on one side then on the other, that he -may get it cooked as soon as possible; even so did he turn himself -about from side to side, thinking all the time how, single-handed as he -was, he should contrive to kill so large a body of men as the wicked -suitors.” - -It looks as though in the interval between the publication of “The -Authoress” (1897) and of the Translation (1900) Butler had changed his -mind; for in the first case the comparison is between Ulysses and a -paunch full, etc., and in the second it is between Ulysses and a man -who turns a paunch full, etc. The second comparison is perhaps one -which a great poet might make. - -In seeing the works through the press I have had the invaluable -assistance of Mr. A. T. Bartholomew of the University Library, -Cambridge, and of Mr. Donald S. Robertson, Fellow of Trinity College, -Cambridge. To both these friends I give my most cordial thanks for the -care and skill exercised by them. Mr. Robertson has found time for the -labour of checking and correcting all the quotations from and -references to the “Iliad” and “Odyssey,” and I believe that it could -not have been better performed. It was, I know, a pleasure for him; and -it would have been a pleasure also for Butler if he could have known -that his work was being shepherded by the son of his old friend, Mr. H. -R. Robertson, who more than half a century ago was a fellow-student -with him at Cary’s School of Art in Streatham Street, Bloomsbury. - -HENRY FESTING JONES. - - 120 MAIDA VALE, W.9. -4th _December_, 1921. - -THE ODYSSEY - - - - -BOOK I - - -THE GODS IN COUNCIL—MINERVA’S VISIT TO ITHACA—THE CHALLENGE FROM -TELEMACHUS TO THE SUITORS. - - -Tell me, O Muse, of that ingenious hero who travelled far and wide -after he had sacked the famous town of Troy. Many cities did he visit, -and many were the nations with whose manners and customs he was -acquainted; moreover he suffered much by sea while trying to save his -own life and bring his men safely home; but do what he might he could -not save his men, for they perished through their own sheer folly in -eating the cattle of the Sun-god Hyperion; so the god prevented them -from ever reaching home. Tell me, too, about all these things, oh -daughter of Jove, from whatsoever source you may know them. - -So now all who escaped death in battle or by shipwreck had got safely -home except Ulysses, and he, though he was longing to return to his -wife and country, was detained by the goddess Calypso, who had got him -into a large cave and wanted to marry him. But as years went by, there -came a time when the gods settled that he should go back to Ithaca; -even then, however, when he was among his own people, his troubles were -not yet over; nevertheless all the gods had now begun to pity him -except Neptune, who still persecuted him without ceasing and would not -let him get home. - -Now Neptune had gone off to the Ethiopians, who are at the world’s end, -and lie in two halves, the one looking West and the other East.1 He had -gone there to accept a hecatomb of sheep and oxen, and was enjoying -himself at his festival; but the other gods met in the house of -Olympian Jove, and the sire of gods and men spoke first. At that moment -he was thinking of Aegisthus, who had been killed by Agamemnon’s son -Orestes; so he said to the other gods: - -“See now, how men lay blame upon us gods for what is after all nothing -but their own folly. Look at Aegisthus; he must needs make love to -Agamemnon’s wife unrighteously and then kill Agamemnon, though he knew -it would be the death of him; for I sent Mercury to warn him not to do -either of these things, inasmuch as Orestes would be sure to take his -revenge when he grew up and wanted to return home. Mercury told him -this in all good will but he would not listen, and now he has paid for -everything in full.” - -Then Minerva said, “Father, son of Saturn, King of kings, it served -Aegisthus right, and so it would any one else who does as he did; but -Aegisthus is neither here nor there; it is for Ulysses that my heart -bleeds, when I think of his sufferings in that lonely sea-girt island, -far away, poor man, from all his friends. It is an island covered with -forest, in the very middle of the sea, and a goddess lives there, -daughter of the magician Atlas, who looks after the bottom of the -ocean, and carries the great columns that keep heaven and earth -asunder. This daughter of Atlas has got hold of poor unhappy Ulysses, -and keeps trying by every kind of blandishment to make him forget his -home, so that he is tired of life, and thinks of nothing but how he may -once more see the smoke of his own chimneys. You, sir, take no heed of -this, and yet when Ulysses was before Troy did he not propitiate you -with many a burnt sacrifice? Why then should you keep on being so angry -with him?” - -And Jove said, “My child, what are you talking about? How can I forget -Ulysses than whom there is no more capable man on earth, nor more -liberal in his offerings to the immortal gods that live in heaven? Bear -in mind, however, that Neptune is still furious with Ulysses for having -blinded an eye of Polyphemus king of the Cyclopes. Polyphemus is son to -Neptune by the nymph Thoosa, daughter to the sea-king Phorcys; -therefore though he will not kill Ulysses outright, he torments him by -preventing him from getting home. Still, let us lay our heads together -and see how we can help him to return; Neptune will then be pacified, -for if we are all of a mind he can hardly stand out against us.” - -And Minerva said, “Father, son of Saturn, King of kings, if, then, the -gods now mean that Ulysses should get home, we should first send -Mercury to the Ogygian island to tell Calypso that we have made up our -minds and that he is to return. In the meantime I will go to Ithaca, to -put heart into Ulysses’ son Telemachus; I will embolden him to call the -Achaeans in assembly, and speak out to the suitors of his mother -Penelope, who persist in eating up any number of his sheep and oxen; I -will also conduct him to Sparta and to Pylos, to see if he can hear -anything about the return of his dear father—for this will make people -speak well of him.” - -So saying she bound on her glittering golden sandals, imperishable, -with which she can fly like the wind over land or sea; she grasped the -redoubtable bronze-shod spear, so stout and sturdy and strong, -wherewith she quells the ranks of heroes who have displeased her, and -down she darted from the topmost summits of Olympus, whereon forthwith -she was in Ithaca, at the gateway of Ulysses’ house, disguised as a -visitor, Mentes, chief of the Taphians, and she held a bronze spear in -her hand. There she found the lordly suitors seated on hides of the -oxen which they had killed and eaten, and playing draughts in front of -the house. Men-servants and pages were bustling about to wait upon -them, some mixing wine with water in the mixing-bowls, some cleaning -down the tables with wet sponges and laying them out again, and some -cutting up great quantities of meat. - -Telemachus saw her long before any one else did. He was sitting moodily -among the suitors thinking about his brave father, and how he would -send them flying out of the house, if he were to come to his own again -and be honoured as in days gone by. Thus brooding as he sat among them, -he caught sight of Minerva and went straight to the gate, for he was -vexed that a stranger should be kept waiting for admittance. He took -her right hand in his own, and bade her give him her spear. “Welcome,” -said he, “to our house, and when you have partaken of food you shall -tell us what you have come for.” - -He led the way as he spoke, and Minerva followed him. When they were -within he took her spear and set it in the spear-stand against a strong -bearing-post along with the many other spears of his unhappy father, -and he conducted her to a richly decorated seat under which he threw a -cloth of damask. There was a footstool also for her feet,2 and he set -another seat near her for himself, away from the suitors, that she -might not be annoyed while eating by their noise and insolence, and -that he might ask her more freely about his father. - -A maid servant then brought them water in a beautiful golden ewer and -poured it into a silver basin for them to wash their hands, and she -drew a clean table beside them. An upper servant brought them bread, -and offered them many good things of what there was in the house, the -carver fetched them plates of all manner of meats and set cups of gold -by their side, and a manservant brought them wine and poured it out for -them. - - -Then the suitors came in and took their places on the benches and -seats.3 Forthwith men servants poured water over their hands, maids -went round with the bread-baskets, pages filled the mixing-bowls with -wine and water, and they laid their hands upon the good things that -were before them. As soon as they had had enough to eat and drink they -wanted music and dancing, which are the crowning embellishments of a -banquet, so a servant brought a lyre to Phemius, whom they compelled -perforce to sing to them. As soon as he touched his lyre and began to -sing Telemachus spoke low to Minerva, with his head close to hers that -no man might hear. - -“I hope, sir,” said he, “that you will not be offended with what I am -going to say. Singing comes cheap to those who do not pay for it, and -all this is done at the cost of one whose bones lie rotting in some -wilderness or grinding to powder in the surf. If these men were to see -my father come back to Ithaca they would pray for longer legs rather -than a longer purse, for money would not serve them; but he, alas, has -fallen on an ill fate, and even when people do sometimes say that he is -coming, we no longer heed them; we shall never see him again. And now, -sir, tell me and tell me true, who you are and where you come from. -Tell me of your town and parents, what manner of ship you came in, how -your crew brought you to Ithaca, and of what nation they declared -themselves to be—for you cannot have come by land. Tell me also truly, -for I want to know, are you a stranger to this house, or have you been -here in my father’s time? In the old days we had many visitors for my -father went about much himself.” - -And Minerva answered, “I will tell you truly and particularly all about -it. I am Mentes, son of Anchialus, and I am King of the Taphians. I -have come here with my ship and crew, on a voyage to men of a foreign -tongue being bound for Temesa4 with a cargo of iron, and I shall bring -back copper. As for my ship, it lies over yonder off the open country -away from the town, in the harbour Rheithron5 under the wooded mountain -Neritum.6 Our fathers were friends before us, as old Laertes will tell -you, if you will go and ask him. They say, however, that he never comes -to town now, and lives by himself in the country, faring hardly, with -an old woman to look after him and get his dinner for him, when he -comes in tired from pottering about his vineyard. They told me your -father was at home again, and that was why I came, but it seems the -gods are still keeping him back, for he is not dead yet not on the -mainland. It is more likely he is on some sea-girt island in mid ocean, -or a prisoner among savages who are detaining him against his will. I -am no prophet, and know very little about omens, but I speak as it is -borne in upon me from heaven, and assure you that he will not be away -much longer; for he is a man of such resource that even though he were -in chains of iron he would find some means of getting home again. But -tell me, and tell me true, can Ulysses really have such a fine looking -fellow for a son? You are indeed wonderfully like him about the head -and eyes, for we were close friends before he set sail for Troy where -the flower of all the Argives went also. Since that time we have never -either of us seen the other.” - -“My mother,” answered Telemachus, “tells me I am son to Ulysses, but it -is a wise child that knows his own father. Would that I were son to one -who had grown old upon his own estates, for, since you ask me, there is -no more ill-starred man under heaven than he who they tell me is my -father.” - -And Minerva said, “There is no fear of your race dying out yet, while -Penelope has such a fine son as you are. But tell me, and tell me true, -what is the meaning of all this feasting, and who are these people? -What is it all about? Have you some banquet, or is there a wedding in -the family—for no one seems to be bringing any provisions of his own? -And the guests—how atrociously they are behaving; what riot they make -over the whole house; it is enough to disgust any respectable person -who comes near them.” - -“Sir,” said Telemachus, “as regards your question, so long as my father -was here it was well with us and with the house, but the gods in their -displeasure have willed it otherwise, and have hidden him away more -closely than mortal man was ever yet hidden. I could have borne it -better even though he were dead, if he had fallen with his men before -Troy, or had died with friends around him when the days of his fighting -were done; for then the Achaeans would have built a mound over his -ashes, and I should myself have been heir to his renown; but now the -storm-winds have spirited him away we know not whither; he is gone -without leaving so much as a trace behind him, and I inherit nothing -but dismay. Nor does the matter end simply with grief for the loss of -my father; heaven has laid sorrows upon me of yet another kind; for the -chiefs from all our islands, Dulichium, Same, and the woodland island -of Zacynthus, as also all the principal men of Ithaca itself, are -eating up my house under the pretext of paying their court to my -mother, who will neither point blank say that she will not marry,7 nor -yet bring matters to an end; so they are making havoc of my estate, and -before long will do so also with myself.” - -“Is that so?” exclaimed Minerva, “then you do indeed want Ulysses home -again. Give him his helmet, shield, and a couple of lances, and if he -is the man he was when I first knew him in our house, drinking and -making merry, he would soon lay his hands about these rascally suitors, -were he to stand once more upon his own threshold. He was then coming -from Ephyra, where he had been to beg poison for his arrows from Ilus, -son of Mermerus. Ilus feared the ever-living gods and would not give -him any, but my father let him have some, for he was very fond of him. -If Ulysses is the man he then was these suitors will have a short -shrift and a sorry wedding. - -“But there! It rests with heaven to determine whether he is to return, -and take his revenge in his own house or no; I would, however, urge you -to set about trying to get rid of these suitors at once. Take my -advice, call the Achaean heroes in assembly to-morrow morning—lay your -case before them, and call heaven to bear you witness. Bid the suitors -take themselves off, each to his own place, and if your mother’s mind -is set on marrying again, let her go back to her father, who will find -her a husband and provide her with all the marriage gifts that so dear -a daughter may expect. As for yourself, let me prevail upon you to take -the best ship you can get, with a crew of twenty men, and go in quest -of your father who has so long been missing. Some one may tell you -something, or (and people often hear things in this way) some -heaven-sent message may direct you. First go to Pylos and ask Nestor; -thence go on to Sparta and visit Menelaus, for he got home last of all -the Achaeans; if you hear that your father is alive and on his way -home, you can put up with the waste these suitors will make for yet -another twelve months. If on the other hand you hear of his death, come -home at once, celebrate his funeral rites with all due pomp, build a -barrow to his memory, and make your mother marry again. Then, having -done all this, think it well over in your mind how, by fair means or -foul, you may kill these suitors in your own house. You are too old to -plead infancy any longer; have you not heard how people are singing -Orestes’ praises for having killed his father’s murderer Aegisthus? You -are a fine, smart looking fellow; show your mettle, then, and make -yourself a name in story. Now, however, I must go back to my ship and -to my crew, who will be impatient if I keep them waiting longer; think -the matter over for yourself, and remember what I have said to you.” - -“Sir,” answered Telemachus, “it has been very kind of you to talk to me -in this way, as though I were your own son, and I will do all you tell -me; I know you want to be getting on with your voyage, but stay a -little longer till you have taken a bath and refreshed yourself. I will -then give you a present, and you shall go on your way rejoicing; I will -give you one of great beauty and value—a keepsake such as only dear -friends give to one another.” - -Minerva answered, “Do not try to keep me, for I would be on my way at -once. As for any present you may be disposed to make me, keep it till I -come again, and I will take it home with me. You shall give me a very -good one, and I will give you one of no less value in return.” - -With these words she flew away like a bird into the air, but she had -given Telemachus courage, and had made him think more than ever about -his father. He felt the change, wondered at it, and knew that the -stranger had been a god, so he went straight to where the suitors were -sitting. - -Phemius was still singing, and his hearers sat rapt in silence as he -told the sad tale of the return from Troy, and the ills Minerva had -laid upon the Achaeans. Penelope, daughter of Icarius, heard his song -from her room upstairs, and came down by the great staircase, not -alone, but attended by two of her handmaids. When she reached the -suitors she stood by one of the bearing posts that supported the roof -of the cloisters8 with a staid maiden on either side of her. She held a -veil, moreover, before her face, and was weeping bitterly. - -“Phemius,” she cried, “you know many another feat of gods and heroes, -such as poets love to celebrate. Sing the suitors some one of these, -and let them drink their wine in silence, but cease this sad tale, for -it breaks my sorrowful heart, and reminds me of my lost husband whom I -mourn ever without ceasing, and whose name was great over all Hellas -and middle Argos.”9 - -“Mother,” answered Telemachus, “let the bard sing what he has a mind -to; bards do not make the ills they sing of; it is Jove, not they, who -makes them, and who sends weal or woe upon mankind according to his own -good pleasure. This fellow means no harm by singing the ill-fated -return of the Danaans, for people always applaud the latest songs most -warmly. Make up your mind to it and bear it; Ulysses is not the only -man who never came back from Troy, but many another went down as well -as he. Go, then, within the house and busy yourself with your daily -duties, your loom, your distaff, and the ordering of your servants; for -speech is man’s matter, and mine above all others 10—for it is I who am -master here.” - -She went wondering back into the house, and laid her son’s saying in -her heart. Then, going upstairs with her handmaids into her room, she -mourned her dear husband till Minerva shed sweet sleep over her eyes. -But the suitors were clamorous throughout the covered cloisters11, and -prayed each one that he might be her bed fellow. - -Then Telemachus spoke, “Shameless,” he cried, “and insolent suitors, -let us feast at our pleasure now, and let there be no brawling, for it -is a rare thing to hear a man with such a divine voice as Phemius has; -but in the morning meet me in full assembly that I may give you formal -notice to depart, and feast at one another’s houses, turn and turn -about, at your own cost. If on the other hand you choose to persist in -spunging upon one man, heaven help me, but Jove shall reckon with you -in full, and when you fall in my father’s house there shall be no man -to avenge you.” - -The suitors bit their lips as they heard him, and marvelled at the -boldness of his speech. Then, Antinous, son of Eupeithes, said, “The -gods seem to have given you lessons in bluster and tall talking; may -Jove never grant you to be chief in Ithaca as your father was before -you.” - -Telemachus answered, “Antinous, do not chide with me, but, god willing, -I will be chief too if I can. Is this the worst fate you can think of -for me? It is no bad thing to be a chief, for it brings both riches and -honour. Still, now that Ulysses is dead there are many great men in -Ithaca both old and young, and some other may take the lead among them; -nevertheless I will be chief in my own house, and will rule those whom -Ulysses has won for me.” - -Then Eurymachus, son of Polybus, answered, “It rests with heaven to -decide who shall be chief among us, but you shall be master in your own -house and over your own possessions; no one while there is a man in -Ithaca shall do you violence nor rob you. And now, my good fellow, I -want to know about this stranger. What country does he come from? Of -what family is he, and where is his estate? Has he brought you news -about the return of your father, or was he on business of his own? He -seemed a well to do man, but he hurried off so suddenly that he was -gone in a moment before we could get to know him.” - -“My father is dead and gone,” answered Telemachus, “and even if some -rumour reaches me I put no more faith in it now. My mother does indeed -sometimes send for a soothsayer and question him, but I give his -prophecyings no heed. As for the stranger, he was Mentes, son of -Anchialus, chief of the Taphians, an old friend of my father’s.” But in -his heart he knew that it had been the goddess. - -The suitors then returned to their singing and dancing until the -evening; but when night fell upon their pleasuring they went home to -bed each in his own abode.12 Telemachus’s room was high up in a tower13 -that looked on to the outer court; hither, then, he hied, brooding and -full of thought. A good old woman, Euryclea, daughter of Ops, the son -of Pisenor, went before him with a couple of blazing torches. Laertes -had bought her with his own money when she was quite young; he gave the -worth of twenty oxen for her, and shewed as much respect to her in his -household as he did to his own wedded wife, but he did not take her to -his bed for he feared his wife’s resentment.14 She it was who now -lighted Telemachus to his room, and she loved him better than any of -the other women in the house did, for she had nursed him when he was a -baby. He opened the door of his bed room and sat down upon the bed; as -he took off his shirt15 he gave it to the good old woman, who folded it -tidily up, and hung it for him over a peg by his bed side, after which -she went out, pulled the door to by a silver catch, and drew the bolt -home by means of the strap.16 But Telemachus as he lay covered with a -woollen fleece kept thinking all night through of his intended voyage -and of the counsel that Minerva had given him. - - - - -BOOK II - - -ASSEMBLY OF THE PEOPLE OF ITHACA—SPEECHES OF TELEMACHUS AND OF THE -SUITORS—TELEMACHUS MAKES HIS PREPARATIONS AND STARTS FOR PYLOS WITH -MINERVA DISGUISED AS MENTOR. - - -Now when the child of morning, rosy-fingered Dawn, appeared Telemachus -rose and dressed himself. He bound his sandals on to his comely feet, -girded his sword about his shoulder, and left his room looking like an -immortal god. He at once sent the criers round to call the people in -assembly, so they called them and the people gathered thereon; then, -when they were got together, he went to the place of assembly spear in -hand—not alone, for his two hounds went with him. Minerva endowed him -with a presence of such divine comeliness that all marvelled at him as -he went by, and when he took his place in his father’s seat even the -oldest councillors made way for him. - -Aegyptius, a man bent double with age, and of infinite experience, was -the first to speak. His son Antiphus had gone with Ulysses to Ilius, -land of noble steeds, but the savage Cyclops had killed him when they -were all shut up in the cave, and had cooked his last dinner for him.17 -He had three sons left, of whom two still worked on their father’s -land, while the third, Eurynomus, was one of the suitors; nevertheless -their father could not get over the loss of Antiphus, and was still -weeping for him when he began his speech. - -“Men of Ithaca,” he said, “hear my words. From the day Ulysses left us -there has been no meeting of our councillors until now; who then can it -be, whether old or young, that finds it so necessary to convene us? Has -he got wind of some host approaching, and does he wish to warn us, or -would he speak upon some other matter of public moment? I am sure he is -an excellent person, and I hope Jove will grant him his heart’s -desire.” - -Telemachus took this speech as of good omen and rose at once, for he -was bursting with what he had to say. He stood in the middle of the -assembly and the good herald Pisenor brought him his staff. Then, -turning to Aegyptius, “Sir,” said he, “it is I, as you will shortly -learn, who have convened you, for it is I who am the most aggrieved. I -have not got wind of any host approaching about which I would warn you, -nor is there any matter of public moment on which I would speak. My -grievance is purely personal, and turns on two great misfortunes which -have fallen upon my house. The first of these is the loss of my -excellent father, who was chief among all you here present, and was -like a father to every one of you; the second is much more serious, and -ere long will be the utter ruin of my estate. The sons of all the chief -men among you are pestering my mother to marry them against her will. -They are afraid to go to her father Icarius, asking him to choose the -one he likes best, and to provide marriage gifts for his daughter, but -day by day they keep hanging about my father’s house, sacrificing our -oxen, sheep, and fat goats for their banquets, and never giving so much -as a thought to the quantity of wine they drink. No estate can stand -such recklessness; we have now no Ulysses to ward off harm from our -doors, and I cannot hold my own against them. I shall never all my days -be as good a man as he was, still I would indeed defend myself if I had -power to do so, for I cannot stand such treatment any longer; my house -is being disgraced and ruined. Have respect, therefore, to your own -consciences and to public opinion. Fear, too, the wrath of heaven, lest -the gods should be displeased and turn upon you. I pray you by Jove and -Themis, who is the beginning and the end of councils, [do not] hold -back, my friends, and leave me singlehanded18—unless it be that my -brave father Ulysses did some wrong to the Achaeans which you would now -avenge on me, by aiding and abetting these suitors. Moreover, if I am -to be eaten out of house and home at all, I had rather you did the -eating yourselves, for I could then take action against you to some -purpose, and serve you with notices from house to house till I got paid -in full, whereas now I have no remedy.”19 - -With this Telemachus dashed his staff to the ground and burst into -tears. Every one was very sorry for him, but they all sat still and no -one ventured to make him an angry answer, save only Antinous, who spoke -thus: - -“Telemachus, insolent braggart that you are, how dare you try to throw -the blame upon us suitors? It is your mother’s fault not ours, for she -is a very artful woman. This three years past, and close on four, she -had been driving us out of our minds, by encouraging each one of us, -and sending him messages without meaning one word of what she says. And -then there was that other trick she played us. She set up a great -tambour frame in her room, and began to work on an enormous piece of -fine needlework. ‘Sweet hearts,’ said she, ‘Ulysses is indeed dead, -still do not press me to marry again immediately, wait—for I would not -have skill in needlework perish unrecorded—till I have completed a pall -for the hero Laertes, to be in readiness against the time when death -shall take him. He is very rich, and the women of the place will talk -if he is laid out without a pall.’ - -“This was what she said, and we assented; whereon we could see her -working on her great web all day long, but at night she would unpick -the stitches again by torchlight. She fooled us in this way for three -years and we never found her out, but as time wore on and she was now -in her fourth year, one of her maids who knew what she was doing told -us, and we caught her in the act of undoing her work, so she had to -finish it whether she would or no. The suitors, therefore, make you -this answer, that both you and the Achaeans may understand—‘Send your -mother away, and bid her marry the man of her own and of her father’s -choice’; for I do not know what will happen if she goes on plaguing us -much longer with the airs she gives herself on the score of the -accomplishments Minerva has taught her, and because she is so clever. -We never yet heard of such a woman; we know all about Tyro, Alcmena, -Mycene, and the famous women of old, but they were nothing to your -mother any one of them. It was not fair of her to treat us in that way, -and as long as she continues in the mind with which heaven has now -endowed her, so long shall we go on eating up your estate; and I do not -see why she should change, for she gets all the honour and glory, and -it is you who pay for it, not she. Understand, then, that we will not -go back to our lands, neither here nor elsewhere, till she has made her -choice and married some one or other of us.” - -Telemachus answered, “Antinous, how can I drive the mother who bore me -from my father’s house? My father is abroad and we do not know whether -he is alive or dead. It will be hard on me if I have to pay Icarius the -large sum which I must give him if I insist on sending his daughter -back to him. Not only will he deal rigorously with me, but heaven will -also punish me; for my mother when she leaves the house will call on -the Erinyes to avenge her; besides, it would not be a creditable thing -to do, and I will have nothing to say to it. If you choose to take -offence at this, leave the house and feast elsewhere at one another’s -houses at your own cost turn and turn about. If, on the other hand, you -elect to persist in spunging upon one man, heaven help me, but Jove -shall reckon with you in full, and when you fall in my father’s house -there shall be no man to avenge you.” - -As he spoke Jove sent two eagles from the top of the mountain, and they -flew on and on with the wind, sailing side by side in their own lordly -flight. When they were right over the middle of the assembly they -wheeled and circled about, beating the air with their wings and glaring -death into the eyes of them that were below; then, fighting fiercely -and tearing at one another, they flew off towards the right over the -town. The people wondered as they saw them, and asked each other what -all this might be; whereon Halitherses, who was the best prophet and -reader of omens among them, spoke to them plainly and in all honesty, -saying: - -“Hear me, men of Ithaca, and I speak more particularly to the suitors, -for I see mischief brewing for them. Ulysses is not going to be away -much longer; indeed he is close at hand to deal out death and -destruction, not on them alone, but on many another of us who live in -Ithaca. Let us then be wise in time, and put a stop to this wickedness -before he comes. Let the suitors do so of their own accord; it will be -better for them, for I am not prophesying without due knowledge; -everything has happened to Ulysses as I foretold when the Argives set -out for Troy, and he with them. I said that after going through much -hardship and losing all his men he should come home again in the -twentieth year and that no one would know him; and now all this is -coming true.” - -Eurymachus son of Polybus then said, “Go home, old man, and prophesy to -your own children, or it may be worse for them. I can read these omens -myself much better than you can; birds are always flying about in the -sunshine somewhere or other, but they seldom mean anything. Ulysses has -died in a far country, and it is a pity you are not dead along with -him, instead of prating here about omens and adding fuel to the anger -of Telemachus which is fierce enough as it is. I suppose you think he -will give you something for your family, but I tell you—and it shall -surely be—when an old man like you, who should know better, talks a -young one over till he becomes troublesome, in the first place his -young friend will only fare so much the worse—he will take nothing by -it, for the suitors will prevent this—and in the next, we will lay a -heavier fine, sir, upon yourself than you will at all like paying, for -it will bear hardly upon you. As for Telemachus, I warn him in the -presence of you all to send his mother back to her father, who will -find her a husband and provide her with all the marriage gifts so dear -a daughter may expect. Till then we shall go on harassing him with our -suit; for we fear no man, and care neither for him, with all his fine -speeches, nor for any fortune-telling of yours. You may preach as much -as you please, but we shall only hate you the more. We shall go back -and continue to eat up Telemachus’s estate without paying him, till -such time as his mother leaves off tormenting us by keeping us day -after day on the tiptoe of expectation, each vying with the other in -his suit for a prize of such rare perfection. Besides we cannot go -after the other women whom we should marry in due course, but for the -way in which she treats us.” - -Then Telemachus said, “Eurymachus, and you other suitors, I shall say -no more, and entreat you no further, for the gods and the people of -Ithaca now know my story. Give me, then, a ship and a crew of twenty -men to take me hither and thither, and I will go to Sparta and to Pylos -in quest of my father who has so long been missing. Some one may tell -me something, or (and people often hear things in this way) some -heaven-sent message may direct me. If I can hear of him as alive and on -his way home I will put up with the waste you suitors will make for yet -another twelve months. If on the other hand I hear of his death, I will -return at once, celebrate his funeral rites with all due pomp, build a -barrow to his memory, and make my mother marry again.” - -With these words he sat down, and Mentor20 who had been a friend of -Ulysses, and had been left in charge of everything with full authority -over the servants, rose to speak. He, then, plainly and in all honesty -addressed them thus: - -“Hear me, men of Ithaca, I hope that you may never have a kind and -well-disposed ruler any more, nor one who will govern you equitably; I -hope that all your chiefs henceforward may be cruel and unjust, for -there is not one of you but has forgotten Ulysses, who ruled you as -though he were your father. I am not half so angry with the suitors, -for if they choose to do violence in the naughtiness of their hearts, -and wager their heads that Ulysses will not return, they can take the -high hand and eat up his estate, but as for you others I am shocked at -the way in which you all sit still without even trying to stop such -scandalous goings on—which you could do if you chose, for you are many -and they are few.” - -Leiocritus, son of Evenor, answered him saying, “Mentor, what folly is -all this, that you should set the people to stay us? It is a hard thing -for one man to fight with many about his victuals. Even though Ulysses -himself were to set upon us while we are feasting in his house, and do -his best to oust us, his wife, who wants him back so very badly, would -have small cause for rejoicing, and his blood would be upon his own -head if he fought against such great odds. There is no sense in what -you have been saying. Now, therefore, do you people go about your -business, and let his father’s old friends, Mentor and Halitherses, -speed this boy on his journey, if he goes at all—which I do not think -he will, for he is more likely to stay where he is till some one comes -and tells him something.” - -On this he broke up the assembly, and every man went back to his own -abode, while the suitors returned to the house of Ulysses. - -Then Telemachus went all alone by the sea side, washed his hands in the -grey waves, and prayed to Minerva. - -“Hear me,” he cried, “you god who visited me yesterday, and bade me -sail the seas in search of my father who has so long been missing. I -would obey you, but the Achaeans, and more particularly the wicked -suitors, are hindering me that I cannot do so.” - -As he thus prayed, Minerva came close up to him in the likeness and -with the voice of Mentor. “Telemachus,” said she, “if you are made of -the same stuff as your father you will be neither fool nor coward -henceforward, for Ulysses never broke his word nor left his work half -done. If, then, you take after him, your voyage will not be fruitless, -but unless you have the blood of Ulysses and of Penelope in your veins -I see no likelihood of your succeeding. Sons are seldom as good men as -their fathers; they are generally worse, not better; still, as you are -not going to be either fool or coward henceforward, and are not -entirely without some share of your father’s wise discernment, I look -with hope upon your undertaking. But mind you never make common cause -with any of those foolish suitors, for they have neither sense nor -virtue, and give no thought to death and to the doom that will shortly -fall on one and all of them, so that they shall perish on the same day. -As for your voyage, it shall not be long delayed; your father was such -an old friend of mine that I will find you a ship, and will come with -you myself. Now, however, return home, and go about among the suitors; -begin getting provisions ready for your voyage; see everything well -stowed, the wine in jars, and the barley meal, which is the staff of -life, in leathern bags, while I go round the town and beat up -volunteers at once. There are many ships in Ithaca both old and new; I -will run my eye over them for you and will choose the best; we will get -her ready and will put out to sea without delay.” - -Thus spoke Minerva daughter of Jove, and Telemachus lost no time in -doing as the goddess told him. He went moodily home, and found the -suitors flaying goats and singeing pigs in the outer court. Antinous -came up to him at once and laughed as he took his hand in his own, -saying, “Telemachus, my fine fire-eater, bear no more ill blood neither -in word nor deed, but eat and drink with us as you used to do. The -Achaeans will find you in everything—a ship and a picked crew to -boot—so that you can set sail for Pylos at once and get news of your -noble father.” - -“Antinous,” answered Telemachus, “I cannot eat in peace, nor take -pleasure of any kind with such men as you are. Was it not enough that -you should waste so much good property of mine while I was yet a boy? -Now that I am older and know more about it, I am also stronger, and -whether here among this people, or by going to Pylos, I will do you all -the harm I can. I shall go, and my going will not be in vain—though, -thanks to you suitors, I have neither ship nor crew of my own, and must -be passenger not captain.” - -As he spoke he snatched his hand from that of Antinous. Meanwhile the -others went on getting dinner ready about the buildings,21 jeering at -him tauntingly as they did so. - -“Telemachus,” said one youngster, “means to be the death of us; I -suppose he thinks he can bring friends to help him from Pylos, or again -from Sparta, where he seems bent on going. Or will he go to Ephyra as -well, for poison to put in our wine and kill us?” - -Another said, “Perhaps if Telemachus goes on board ship, he will be -like his father and perish far from his friends. In this case we should -have plenty to do, for we could then divide up his property amongst us: -as for the house we can let his mother and the man who marries her have -that.” - -This was how they talked. But Telemachus went down into the lofty and -spacious store-room where his father’s treasure of gold and bronze lay -heaped up upon the floor, and where the linen and spare clothes were -kept in open chests. Here, too, there was a store of fragrant olive -oil, while casks of old, well-ripened wine, unblended and fit for a god -to drink, were ranged against the wall in case Ulysses should come home -again after all. The room was closed with well-made doors opening in -the middle; moreover the faithful old house-keeper Euryclea, daughter -of Ops the son of Pisenor, was in charge of everything both night and -day. Telemachus called her to the store-room and said: - -“Nurse, draw me off some of the best wine you have, after what you are -keeping for my father’s own drinking, in case, poor man, he should -escape death, and find his way home again after all. Let me have twelve -jars, and see that they all have lids; also fill me some well-sewn -leathern bags with barley meal—about twenty measures in all. Get these -things put together at once, and say nothing about it. I will take -everything away this evening as soon as my mother has gone upstairs for -the night. I am going to Sparta and to Pylos to see if I can hear -anything about the return of my dear father.” - -When Euryclea heard this she began to cry, and spoke fondly to him, -saying, “My dear child, what ever can have put such notion as that into -your head? Where in the world do you want to go to—you, who are the one -hope of the house? Your poor father is dead and gone in some foreign -country nobody knows where, and as soon as your back is turned these -wicked ones here will be scheming to get you put out of the way, and -will share all your possessions among themselves; stay where you are -among your own people, and do not go wandering and worrying your life -out on the barren ocean.” - -“Fear not, nurse,” answered Telemachus, “my scheme is not without -heaven’s sanction; but swear that you will say nothing about all this -to my mother, till I have been away some ten or twelve days, unless she -hears of my having gone, and asks you; for I do not want her to spoil -her beauty by crying.” - -The old woman swore most solemnly that she would not, and when she had -completed her oath, she began drawing off the wine into jars, and -getting the barley meal into the bags, while Telemachus went back to -the suitors. - -Then Minerva bethought her of another matter. She took his shape, and -went round the town to each one of the crew, telling them to meet at -the ship by sundown. She went also to Noemon son of Phronius, and asked -him to let her have a ship—which he was very ready to do. When the sun -had set and darkness was over all the land, she got the ship into the -water, put all the tackle on board her that ships generally carry, and -stationed her at the end of the harbour. Presently the crew came up, -and the goddess spoke encouragingly to each of them. - -Furthermore she went to the house of Ulysses, and threw the suitors -into a deep slumber. She caused their drink to fuddle them, and made -them drop their cups from their hands, so that instead of sitting over -their wine, they went back into the town to sleep, with their eyes -heavy and full of drowsiness. Then she took the form and voice of -Mentor, and called Telemachus to come outside. - -“Telemachus,” said she, “the men are on board and at their oars, -waiting for you to give your orders, so make haste and let us be off.” - -On this she led the way, while Telemachus followed in her steps. When -they got to the ship they found the crew waiting by the water side, and -Telemachus said, “Now my men, help me to get the stores on board; they -are all put together in the cloister, and my mother does not know -anything about it, nor any of the maid servants except one.” - -With these words he led the way and the others followed after. When -they had brought the things as he told them, Telemachus went on board, -Minerva going before him and taking her seat in the stern of the -vessel, while Telemachus sat beside her. Then the men loosed the -hawsers and took their places on the benches. Minerva sent them a fair -wind from the West,22 that whistled over the deep blue waves23 whereon -Telemachus told them to catch hold of the ropes and hoist sail, and -they did as he told them. They set the mast in its socket in the cross -plank, raised it, and made it fast with the forestays; then they -hoisted their white sails aloft with ropes of twisted ox hide. As the -sail bellied out with the wind, the ship flew through the deep blue -water, and the foam hissed against her bows as she sped onward. Then -they made all fast throughout the ship, filled the mixing bowls to the -brim, and made drink offerings to the immortal gods that are from -everlasting, but more particularly to the grey-eyed daughter of Jove. - -Thus, then, the ship sped on her way through the watches of the night -from dark till dawn. - - - - -BOOK III - - -TELEMACHUS VISITS NESTOR AT PYLOS. - - -but as the sun was rising from the fair sea24 into the firmament of -heaven to shed light on mortals and immortals, they reached Pylos the -city of Neleus. Now the people of Pylos were gathered on the sea shore -to offer sacrifice of black bulls to Neptune lord of the Earthquake. -There were nine guilds with five hundred men in each, and there were -nine bulls to each guild. As they were eating the inward meats25 and -burning the thigh bones [on the embers] in the name of Neptune, -Telemachus and his crew arrived, furled their sails, brought their ship -to anchor, and went ashore. - -Minerva led the way and Telemachus followed her. Presently she said, -“Telemachus, you must not be in the least shy or nervous; you have -taken this voyage to try and find out where your father is buried and -how he came by his end; so go straight up to Nestor that we may see -what he has got to tell us. Beg of him to speak the truth, and he will -tell no lies, for he is an excellent person.” - -“But how, Mentor,” replied Telemachus, “dare I go up to Nestor, and how -am I to address him? I have never yet been used to holding long -conversations with people, and am ashamed to begin questioning one who -is so much older than myself.” - -“Some things, Telemachus,” answered Minerva, “will be suggested to you -by your own instinct, and heaven will prompt you further; for I am -assured that the gods have been with you from the time of your birth -until now.” - -She then went quickly on, and Telemachus followed in her steps till -they reached the place where the guilds of the Pylian people were -assembled. There they found Nestor sitting with his sons, while his -company round him were busy getting dinner ready, and putting pieces of -meat on to the spits26 while other pieces were cooking. When they saw -the strangers they crowded round them, took them by the hand and bade -them take their places. Nestor’s son Pisistratus at once offered his -hand to each of them, and seated them on some soft sheepskins that were -lying on the sands near his father and his brother Thrasymedes. Then he -gave them their portions of the inward meats and poured wine for them -into a golden cup, handing it to Minerva first, and saluting her at the -same time. - -“Offer a prayer, sir,” said he, “to King Neptune, for it is his feast -that you are joining; when you have duly prayed and made your drink -offering, pass the cup to your friend that he may do so also. I doubt -not that he too lifts his hands in prayer, for man cannot live without -God in the world. Still he is younger than you are, and is much of an -age with myself, so I will give you the precedence.” - -As he spoke he handed her the cup. Minerva thought it very right and -proper of him to have given it to herself first;27 she accordingly -began praying heartily to Neptune. “O thou,” she cried, “that -encirclest the earth, vouchsafe to grant the prayers of thy servants -that call upon thee. More especially we pray thee send down thy grace -on Nestor and on his sons; thereafter also make the rest of the Pylian -people some handsome return for the goodly hecatomb they are offering -you. Lastly, grant Telemachus and myself a happy issue, in respect of -the matter that has brought us in our ship to Pylos.” - -When she had thus made an end of praying, she handed the cup to -Telemachus and he prayed likewise. By and by, when the outer meats were -roasted and had been taken off the spits, the carvers gave every man -his portion and they all made an excellent dinner. As soon as they had -had enough to eat and drink, Nestor, knight of Gerene, began to speak. - -“Now,” said he, “that our guests have done their dinner, it will be -best to ask them who they are. Who, then, sir strangers, are you, and -from what port have you sailed? Are you traders? or do you sail the -seas as rovers with your hand against every man, and every man’s hand -against you?” - -Telemachus answered boldly, for Minerva had given him courage to ask -about his father and get himself a good name. - -“Nestor,” said he, “son of Neleus, honour to the Achaean name, you ask -whence we come, and I will tell you. We come from Ithaca under -Neritum,28 and the matter about which I would speak is of private not -public import. I seek news of my unhappy father Ulysses, who is said to -have sacked the town of Troy in company with yourself. We know what -fate befell each one of the other heroes who fought at Troy, but as -regards Ulysses heaven has hidden from us the knowledge even that he is -dead at all, for no one can certify us in what place he perished, nor -say whether he fell in battle on the mainland, or was lost at sea amid -the waves of Amphitrite. Therefore I am suppliant at your knees, if -haply you may be pleased to tell me of his melancholy end, whether you -saw it with your own eyes, or heard it from some other traveller, for -he was a man born to trouble. Do not soften things out of any pity for -me, but tell me in all plainness exactly what you saw. If my brave -father Ulysses ever did you loyal service, either by word or deed, when -you Achaeans were harassed among the Trojans, bear it in mind now as in -my favour and tell me truly all.” - -“My friend,” answered Nestor, “you recall a time of much sorrow to my -mind, for the brave Achaeans suffered much both at sea, while -privateering under Achilles, and when fighting before the great city of -king Priam. Our best men all of them fell there—Ajax, Achilles, -Patroclus peer of gods in counsel, and my own dear son Antilochus, a -man singularly fleet of foot and in fight valiant. But we suffered much -more than this; what mortal tongue indeed could tell the whole story? -Though you were to stay here and question me for five years, or even -six, I could not tell you all that the Achaeans suffered, and you would -turn homeward weary of my tale before it ended. Nine long years did we -try every kind of stratagem, but the hand of heaven was against us; -during all this time there was no one who could compare with your -father in subtlety—if indeed you are his son—I can hardly believe my -eyes—and you talk just like him too—no one would say that people of -such different ages could speak so much alike. He and I never had any -kind of difference from first to last neither in camp nor council, but -in singleness of heart and purpose we advised the Argives how all might -be ordered for the best. - -“When, however, we had sacked the city of Priam, and were setting sail -in our ships as heaven had dispersed us, then Jove saw fit to vex the -Argives on their homeward voyage; for they had not all been either wise -or understanding, and hence many came to a bad end through the -displeasure of Jove’s daughter Minerva, who brought about a quarrel -between the two sons of Atreus. - -“The sons of Atreus called a meeting which was not as it should be, for -it was sunset and the Achaeans were heavy with wine. When they -explained why they had called the people together, it seemed that -Menelaus was for sailing homeward at once, and this displeased -Agamemnon, who thought that we should wait till we had offered -hecatombs to appease the anger of Minerva. Fool that he was, he might -have known that he would not prevail with her, for when the gods have -made up their minds they do not change them lightly. So the two stood -bandying hard words, whereon the Achaeans sprang to their feet with a -cry that rent the air, and were of two minds as to what they should do. - -“That night we rested and nursed our anger, for Jove was hatching -mischief against us. But in the morning some of us drew our ships into -the water and put our goods with our women on board, while the rest, -about half in number, stayed behind with Agamemnon. We—the other -half—embarked and sailed; and the ships went well, for heaven had -smoothed the sea. When we reached Tenedos we offered sacrifices to the -gods, for we were longing to get home; cruel Jove, however, did not yet -mean that we should do so, and raised a second quarrel in the course of -which some among us turned their ships back again, and sailed away -under Ulysses to make their peace with Agamemnon; but I, and all the -ships that were with me pressed forward, for I saw that mischief was -brewing. The son of Tydeus went on also with me, and his crews with -him. Later on Menelaus joined us at Lesbos, and found us making up our -minds about our course—for we did not know whether to go outside Chios -by the island of Psyra, keeping this to our left, or inside Chios, over -against the stormy headland of Mimas. So we asked heaven for a sign, -and were shown one to the effect that we should be soonest out of -danger if we headed our ships across the open sea to Euboea. This we -therefore did, and a fair wind sprang up which gave us a quick passage -during the night to Geraestus,29 where we offered many sacrifices to -Neptune for having helped us so far on our way. Four days later Diomed -and his men stationed their ships in Argos, but I held on for Pylos, -and the wind never fell light from the day when heaven first made it -fair for me. - -“Therefore, my dear young friend, I returned without hearing anything -about the others. I know neither who got home safely nor who were lost -but, as in duty bound, I will give you without reserve the reports that -have reached me since I have been here in my own house. They say the -Myrmidons returned home safely under Achilles’ son Neoptolemus; so also -did the valiant son of Poias, Philoctetes. Idomeneus, again, lost no -men at sea, and all his followers who escaped death in the field got -safe home with him to Crete. No matter how far out of the world you -live, you will have heard of Agamemnon and the bad end he came to at -the hands of Aegisthus—and a fearful reckoning did Aegisthus presently -pay. See what a good thing it is for a man to leave a son behind him to -do as Orestes did, who killed false Aegisthus the murderer of his noble -father. You too, then—for you are a tall smart-looking fellow—show your -mettle and make yourself a name in story.” - -“Nestor son of Neleus,” answered Telemachus, “honour to the Achaean -name, the Achaeans applaud Orestes and his name will live through all -time for he has avenged his father nobly. Would that heaven might grant -me to do like vengeance on the insolence of the wicked suitors, who are -ill treating me and plotting my ruin; but the gods have no such -happiness in store for me and for my father, so we must bear it as best -we may.” - -“My friend,” said Nestor, “now that you remind me, I remember to have -heard that your mother has many suitors, who are ill disposed towards -you and are making havoc of your estate. Do you submit to this tamely, -or are public feeling and the voice of heaven against you? Who knows -but what Ulysses may come back after all, and pay these scoundrels in -full, either single-handed or with a force of Achaeans behind him? If -Minerva were to take as great a liking to you as she did to Ulysses -when we were fighting before Troy (for I never yet saw the gods so -openly fond of any one as Minerva then was of your father), if she -would take as good care of you as she did of him, these wooers would -soon some of them forget their wooing.” - -Telemachus answered, “I can expect nothing of the kind; it would be far -too much to hope for. I dare not let myself think of it. Even though -the gods themselves willed it no such good fortune could befall me.” - -On this Minerva said, “Telemachus, what are you talking about? Heaven -has a long arm if it is minded to save a man; and if it were me, I -should not care how much I suffered before getting home, provided I -could be safe when I was once there. I would rather this, than get home -quickly, and then be killed in my own house as Agamemnon was by the -treachery of Aegisthus and his wife. Still, death is certain, and when -a man’s hour is come, not even the gods can save him, no matter how -fond they are of him.” - -“Mentor,” answered Telemachus, “do not let us talk about it any more. -There is no chance of my father’s ever coming back; the gods have long -since counselled his destruction. There is something else, however, -about which I should like to ask Nestor, for he knows much more than -any one else does. They say he has reigned for three generations so -that it is like talking to an immortal. Tell me, therefore, Nestor, and -tell me true; how did Agamemnon come to die in that way? What was -Menelaus doing? And how came false Aegisthus to kill so far better a -man than himself? Was Menelaus away from Achaean Argos, voyaging -elsewhither among mankind, that Aegisthus took heart and killed -Agamemnon?” - -“I will tell you truly,” answered Nestor, “and indeed you have yourself -divined how it all happened. If Menelaus when he got back from Troy had -found Aegisthus still alive in his house, there would have been no -barrow heaped up for him, not even when he was dead, but he would have -been thrown outside the city to dogs and vultures, and not a woman -would have mourned him, for he had done a deed of great wickedness; but -we were over there, fighting hard at Troy, and Aegisthus, who was -taking his ease quietly in the heart of Argos, cajoled Agamemnon’s wife -Clytemnestra with incessant flattery. - -“At first she would have nothing to do with his wicked scheme, for she -was of a good natural disposition;30 moreover there was a bard with -her, to whom Agamemnon had given strict orders on setting out for Troy, -that he was to keep guard over his wife; but when heaven had counselled -her destruction, Aegisthus carried this bard off to a desert island and -left him there for crows and seagulls to batten upon—after which she -went willingly enough to the house of Aegisthus. Then he offered many -burnt sacrifices to the gods, and decorated many temples with -tapestries and gilding, for he had succeeded far beyond his -expectations. - -“Meanwhile Menelaus and I were on our way home from Troy, on good terms -with one another. When we got to Sunium, which is the point of Athens, -Apollo with his painless shafts killed Phrontis the steersman of -Menelaus’ ship (and never man knew better how to handle a vessel in -rough weather) so that he died then and there with the helm in his -hand, and Menelaus, though very anxious to press forward, had to wait -in order to bury his comrade and give him his due funeral rites. -Presently, when he too could put to sea again, and had sailed on as far -as the Malean heads, Jove counselled evil against him and made it blow -hard till the waves ran mountains high. Here he divided his fleet and -took the one half towards Crete where the Cydonians dwell round about -the waters of the river Iardanus. There is a high headland hereabouts -stretching out into the sea from a place called Gortyn, and all along -this part of the coast as far as Phaestus the sea runs high when there -is a south wind blowing, but after Phaestus the coast is more -protected, for a small headland can make a great shelter. Here this -part of the fleet was driven on to the rocks and wrecked; but the crews -just managed to save themselves. As for the other five ships, they were -taken by winds and seas to Egypt, where Menelaus gathered much gold and -substance among people of an alien speech. Meanwhile Aegisthus here at -home plotted his evil deed. For seven years after he had killed -Agamemnon he ruled in Mycene, and the people were obedient under him, -but in the eighth year Orestes came back from Athens to be his bane, -and killed the murderer of his father. Then he celebrated the funeral -rites of his mother and of false Aegisthus by a banquet to the people -of Argos, and on that very day Menelaus came home,31 with as much -treasure as his ships could carry. - -“Take my advice then, and do not go travelling about for long so far -from home, nor leave your property with such dangerous people in your -house; they will eat up everything you have among them, and you will -have been on a fool’s errand. Still, I should advise you by all means -to go and visit Menelaus, who has lately come off a voyage among such -distant peoples as no man could ever hope to get back from, when the -winds had once carried him so far out of his reckoning; even birds -cannot fly the distance in a twelve-month, so vast and terrible are the -seas that they must cross. Go to him, therefore, by sea, and take your -own men with you; or if you would rather travel by land you can have a -chariot, you can have horses, and here are my sons who can escort you -to Lacedaemon where Menelaus lives. Beg of him to speak the truth, and -he will tell you no lies, for he is an excellent person.” - -As he spoke the sun set and it came on dark, whereon Minerva said, -“Sir, all that you have said is well; now, however, order the tongues -of the victims to be cut, and mix wine that we may make drink-offerings -to Neptune, and the other immortals, and then go to bed, for it is bed -time. People should go away early and not keep late hours at a -religious festival.” - -Thus spoke the daughter of Jove, and they obeyed her saying. Men -servants poured water over the hands of the guests, while pages filled -the mixing-bowls with wine and water, and handed it round after giving -every man his drink offering; then they threw the tongues of the -victims into the fire, and stood up to make their drink offerings. When -they had made their offerings and had drunk each as much as he was -minded, Minerva and Telemachus were for going on board their ship, but -Nestor caught them up at once and stayed them. - -“Heaven and the immortal gods,” he exclaimed, “forbid that you should -leave my house to go on board of a ship. Do you think I am so poor and -short of clothes, or that I have so few cloaks and as to be unable to -find comfortable beds both for myself and for my guests? Let me tell -you I have store both of rugs and cloaks, and shall not permit the son -of my old friend Ulysses to camp down on the deck of a ship—not while I -live—nor yet will my sons after me, but they will keep open house as I -have done.” - -Then Minerva answered, “Sir, you have spoken well, and it will be much -better that Telemachus should do as you have said; he, therefore, shall -return with you and sleep at your house, but I must go back to give -orders to my crew, and keep them in good heart. I am the only older -person among them; the rest are all young men of Telemachus’ own age, -who have taken this voyage out of friendship; so I must return to the -ship and sleep there. Moreover to-morrow I must go to the Cauconians -where I have a large sum of money long owing to me. As for Telemachus, -now that he is your guest, send him to Lacedaemon in a chariot, and let -one of your sons go with him. Be pleased to also provide him with your -best and fleetest horses.” - -When she had thus spoken, she flew away in the form of an eagle, and -all marvelled as they beheld it. Nestor was astonished, and took -Telemachus by the hand. “My friend,” said he, “I see that you are going -to be a great hero some day, since the gods wait upon you thus while -you are still so young. This can have been none other of those who -dwell in heaven than Jove’s redoubtable daughter, the Trito-born, who -shewed such favour towards your brave father among the Argives. Holy -queen,” he continued, “vouchsafe to send down thy grace upon myself, my -good wife, and my children. In return, I will offer you in sacrifice a -broad-browed heifer of a year old, unbroken, and never yet brought by -man under the yoke. I will gild her horns, and will offer her up to you -in sacrifice.” - -Thus did he pray, and Minerva heard his prayer. He then led the way to -his own house, followed by his sons and sons in law. When they had got -there and had taken their places on the benches and seats, he mixed -them a bowl of sweet wine that was eleven years old when the -housekeeper took the lid off the jar that held it. As he mixed the -wine, he prayed much and made drink offerings to Minerva, daughter of -Aegis-bearing Jove. Then, when they had made their drink offerings and -had drunk each as much as he was minded, the others went home to bed -each in his own abode; but Nestor put Telemachus to sleep in the room -that was over the gateway along with Pisistratus, who was the only -unmarried son now left him. As for himself, he slept in an inner room -of the house, with the queen his wife by his side. - -Now when the child of morning rosy-fingered Dawn appeared, Nestor left -his couch and took his seat on the benches of white and polished marble -that stood in front of his house. Here aforetime sat Neleus, peer of -gods in counsel, but he was now dead, and had gone to the house of -Hades; so Nestor sat in his seat sceptre in hand, as guardian of the -public weal. His sons as they left their rooms gathered round him, -Echephron, Stratius, Perseus, Aretus, and Thrasymedes; the sixth son -was Pisistratus, and when Telemachus joined them they made him sit with -them. Nestor then addressed them. - -“My sons,” said he, “make haste to do as I shall bid you. I wish first -and foremost to propitiate the great goddess Minerva, who manifested -herself visibly to me during yesterday’s festivities. Go, then, one or -other of you to the plain, tell the stockman to look me out a heifer, -and come on here with it at once. Another must go to Telemachus’ ship, -and invite all the crew, leaving two men only in charge of the vessel. -Some one else will run and fetch Laerceus the goldsmith to gild the -horns of the heifer. The rest, stay all of you where you are; tell the -maids in the house to prepare an excellent dinner, and to fetch seats, -and logs of wood for a burnt offering. Tell them also to bring me some -clear spring water.” - -On this they hurried off on their several errands. The heifer was -brought in from the plain, and Telemachus’s crew came from the ship; -the goldsmith brought the anvil, hammer, and tongs, with which he -worked his gold, and Minerva herself came to accept the sacrifice. -Nestor gave out the gold, and the smith gilded the horns of the heifer -that the goddess might have pleasure in their beauty. Then Stratius and -Echephron brought her in by the horns; Aretus fetched water from the -house in a ewer that had a flower pattern on it, and in his other hand -he held a basket of barley meal; sturdy Thrasymedes stood by with a -sharp axe, ready to strike the heifer, while Perseus held a bucket. -Then Nestor began with washing his hands and sprinkling the barley -meal, and he offered many a prayer to Minerva as he threw a lock from -the heifer’s head upon the fire. - -When they had done praying and sprinkling the barley meal32 Thrasymedes -dealt his blow, and brought the heifer down with a stroke that cut -through the tendons at the base of her neck, whereon the daughters and -daughters in law of Nestor, and his venerable wife Eurydice (she was -eldest daughter to Clymenus) screamed with delight. Then they lifted -the heifer’s head from off the ground, and Pisistratus cut her throat. -When she had done bleeding and was quite dead, they cut her up. They -cut out the thigh bones all in due course, wrapped them round in two -layers of fat, and set some pieces of raw meat on the top of them; then -Nestor laid them upon the wood fire and poured wine over them, while -the young men stood near him with five-pronged spits in their hands. -When the thighs were burned and they had tasted the inward meats, they -cut the rest of the meat up small, put the pieces on the spits and -toasted them over the fire. - -Meanwhile lovely Polycaste, Nestor’s youngest daughter, washed -Telemachus. When she had washed him and anointed him with oil, she -brought him a fair mantle and shirt,33 and he looked like a god as he -came from the bath and took his seat by the side of Nestor. When the -outer meats were done they drew them off the spits and sat down to -dinner where they were waited upon by some worthy henchmen, who kept -pouring them out their wine in cups of gold. As soon as they had had -enough to eat and drink Nestor said, “Sons, put Telemachus’s horses to -the chariot that he may start at once.” - -Thus did he speak, and they did even as he had said, and yoked the -fleet horses to the chariot. The housekeeper packed them up a provision -of bread, wine, and sweet meats fit for the sons of princes. Then -Telemachus got into the chariot, while Pisistratus gathered up the -reins and took his seat beside him. He lashed the horses on and they -flew forward nothing loth into the open country, leaving the high -citadel of Pylos behind them. All that day did they travel, swaying the -yoke upon their necks till the sun went down and darkness was over all -the land. Then they reached Pherae where Diocles lived, who was son to -Ortilochus and grandson to Alpheus. Here they passed the night and -Diocles entertained them hospitably. When the child of morning, -rosy-fingered Dawn, appeared, they again yoked their horses and drove -out through the gateway under the echoing gatehouse.34 Pisistratus -lashed the horses on and they flew forward nothing loth; presently they -came to the corn lands of the open country, and in the course of time -completed their journey, so well did their steeds take them.35 - -Now when the sun had set and darkness was over the land, - - - - -BOOK IV - - -THE VISIT TO KING MENELAUS, WHO TELLS HIS STORY—MEANWHILE THE SUITORS -IN ITHACA PLOT AGAINST TELEMACHUS. - - -they reached the low lying city of Lacedaemon, where they drove -straight to the abode of Menelaus36 [and found him in his own house, -feasting with his many clansmen in honour of the wedding of his son, -and also of his daughter, whom he was marrying to the son of that -valiant warrior Achilles. He had given his consent and promised her to -him while he was still at Troy, and now the gods were bringing the -marriage about; so he was sending her with chariots and horses to the -city of the Myrmidons over whom Achilles’ son was reigning. For his -only son he had found a bride from Sparta,37 the daughter of Alector. -This son, Megapenthes, was born to him of a bondwoman, for heaven -vouchsafed Helen no more children after she had borne Hermione, who was -fair as golden Venus herself. - -So the neighbours and kinsmen of Menelaus were feasting and making -merry in his house. There was a bard also to sing to them and play his -lyre, while two tumblers went about performing in the midst of them -when the man struck up with his tune.38 - -Telemachus and the son of Nestor stayed their horses at the gate, -whereon Eteoneus servant to Menelaus came out, and as soon as he saw -them ran hurrying back into the house to tell his Master. He went close -up to him and said, “Menelaus, there are some strangers come here, two -men, who look like sons of Jove. What are we to do? Shall we take their -horses out, or tell them to find friends elsewhere as they best can?” - -Menelaus was very angry and said, “Eteoneus, son of Boethous, you never -used to be a fool, but now you talk like a simpleton. Take their horses -out, of course, and show the strangers in that they may have supper; -you and I have staid often enough at other people’s houses before we -got back here, where heaven grant that we may rest in peace -henceforward.” - -So Eteoneus bustled back and bade the other servants come with him. -They took their sweating steeds from under the yoke, made them fast to -the mangers, and gave them a feed of oats and barley mixed. Then they -leaned the chariot against the end wall of the courtyard, and led the -way into the house. Telemachus and Pisistratus were astonished when -they saw it, for its splendour was as that of the sun and moon; then, -when they had admired everything to their heart’s content, they went -into the bath room and washed themselves. - -When the servants had washed them and anointed them with oil, they -brought them woollen cloaks and shirts, and the two took their seats by -the side of Menelaus. A maid-servant brought them water in a beautiful -golden ewer, and poured it into a silver basin for them to wash their -hands; and she drew a clean table beside them. An upper servant brought -them bread, and offered them many good things of what there was in the -house, while the carver fetched them plates of all manner of meats and -set cups of gold by their side. - -Menelaus then greeted them saying, “Fall to, and welcome; when you have -done supper I shall ask who you are, for the lineage of such men as you -cannot have been lost. You must be descended from a line of -sceptre-bearing kings, for poor people do not have such sons as you -are.” - -On this he handed them39 a piece of fat roast loin, which had been set -near him as being a prime part, and they laid their hands on the good -things that were before them; as soon as they had had enough to eat and -drink, Telemachus said to the son of Nestor, with his head so close -that no one might hear, “Look, Pisistratus, man after my own heart, see -the gleam of bronze and gold—of amber,40 ivory, and silver. Everything -is so splendid that it is like seeing the palace of Olympian Jove. I am -lost in admiration.” - -Menelaus overheard him and said, “No one, my sons, can hold his own -with Jove, for his house and everything about him is immortal; but -among mortal men—well, there may be another who has as much wealth as I -have, or there may not; but at all events I have travelled much and -have undergone much hardship, for it was nearly eight years before I -could get home with my fleet. I went to Cyprus, Phoenicia and the -Egyptians; I went also to the Ethiopians, the Sidonians, and the -Erembians, and to Libya where the lambs have horns as soon as they are -born, and the sheep lamb down three times a year. Every one in that -country, whether master or man, has plenty of cheese, meat, and good -milk, for the ewes yield all the year round. But while I was travelling -and getting great riches among these people, my brother was secretly -and shockingly murdered through the perfidy of his wicked wife, so that -I have no pleasure in being lord of all this wealth. Whoever your -parents may be they must have told you about all this, and of my heavy -loss in the ruin41 of a stately mansion fully and magnificently -furnished. Would that I had only a third of what I now have so that I -had stayed at home, and all those were living who perished on the plain -of Troy, far from Argos. I often grieve, as I sit here in my house, for -one and all of them. At times I cry aloud for sorrow, but presently I -leave off again, for crying is cold comfort and one soon tires of it. -Yet grieve for these as I may, I do so for one man more than for them -all. I cannot even think of him without loathing both food and sleep, -so miserable does he make me, for no one of all the Achaeans worked so -hard or risked so much as he did. He took nothing by it, and has left a -legacy of sorrow to myself, for he has been gone a long time, and we -know not whether he is alive or dead. His old father, his -long-suffering wife Penelope, and his son Telemachus, whom he left -behind him an infant in arms, are plunged in grief on his account.” - -Thus spoke Menelaus, and the heart of Telemachus yearned as he -bethought him of his father. Tears fell from his eyes as he heard him -thus mentioned, so that he held his cloak before his face with both -hands. When Menelaus saw this he doubted whether to let him choose his -own time for speaking, or to ask him at once and find what it was all -about. - -While he was thus in two minds Helen came down from her high vaulted -and perfumed room, looking as lovely as Diana herself. Adraste brought -her a seat, Alcippe a soft woollen rug while Phylo fetched her the -silver work-box which Alcandra wife of Polybus had given her. Polybus -lived in Egyptian Thebes, which is the richest city in the whole world; -he gave Menelaus two baths, both of pure silver, two tripods, and ten -talents of gold; besides all this, his wife gave Helen some beautiful -presents, to wit, a golden distaff, and a silver work box that ran on -wheels, with a gold band round the top of it. Phylo now placed this by -her side, full of fine spun yarn, and a distaff charged with violet -coloured wool was laid upon the top of it. Then Helen took her seat, -put her feet upon the footstool, and began to question her husband.42 - -“Do we know, Menelaus,” said she, “the names of these strangers who -have come to visit us? Shall I guess right or wrong?—but I cannot help -saying what I think. Never yet have I seen either man or woman so like -somebody else (indeed when I look at him I hardly know what to think) -as this young man is like Telemachus, whom Ulysses left as a baby -behind him, when you Achaeans went to Troy with battle in your hearts, -on account of my most shameless self.” - -“My dear wife,” replied Menelaus, “I see the likeness just as you do. -His hands and feet are just like Ulysses; so is his hair, with the -shape of his head and the expression of his eyes. Moreover, when I was -talking about Ulysses, and saying how much he had suffered on my -account, tears fell from his eyes, and he hid his face in his mantle.” - -Then Pisistratus said, “Menelaus, son of Atreus, you are right in -thinking that this young man is Telemachus, but he is very modest, and -is ashamed to come here and begin opening up discourse with one whose -conversation is so divinely interesting as your own. My father, Nestor, -sent me to escort him hither, for he wanted to know whether you could -give him any counsel or suggestion. A son has always trouble at home -when his father has gone away leaving him without supporters; and this -is how Telemachus is now placed, for his father is absent, and there is -no one among his own people to stand by him.” - -“Bless my heart,” replied Menelaus, “then I am receiving a visit from -the son of a very dear friend, who suffered much hardship for my sake. -I had always hoped to entertain him with most marked distinction when -heaven had granted us a safe return from beyond the seas. I should have -founded a city for him in Argos, and built him a house. I should have -made him leave Ithaca with his goods, his son, and all his people, and -should have sacked for them some one of the neighbouring cities that -are subject to me. We should thus have seen one another continually, -and nothing but death could have interrupted so close and happy an -intercourse. I suppose, however, that heaven grudged us such great good -fortune, for it has prevented the poor fellow from ever getting home at -all.” - -Thus did he speak, and his words set them all a weeping. Helen wept, -Telemachus wept, and so did Menelaus, nor could Pisistratus keep his -eyes from filling, when he remembered his dear brother Antilochus whom -the son of bright Dawn had killed. Thereon he said to Menelaus, - -“Sir, my father Nestor, when we used to talk about you at home, told me -you were a person of rare and excellent understanding. If, then, it be -possible, do as I would urge you. I am not fond of crying while I am -getting my supper. Morning will come in due course, and in the forenoon -I care not how much I cry for those that are dead and gone. This is all -we can do for the poor things. We can only shave our heads for them and -wring the tears from our cheeks. I had a brother who died at Troy; he -was by no means the worst man there; you are sure to have known him—his -name was Antilochus; I never set eyes upon him myself, but they say -that he was singularly fleet of foot and in fight valiant.” - -“Your discretion, my friend,” answered Menelaus, “is beyond your years. -It is plain you take after your father. One can soon see when a man is -son to one whom heaven has blessed both as regards wife and -offspring—and it has blessed Nestor from first to last all his days, -giving him a green old age in his own house, with sons about him who -are both well disposed and valiant. We will put an end therefore to all -this weeping, and attend to our supper again. Let water be poured over -our hands. Telemachus and I can talk with one another fully in the -morning.” - -On this Asphalion, one of the servants, poured water over their hands -and they laid their hands on the good things that were before them. - -Then Jove’s daughter Helen bethought her of another matter. She drugged -the wine with an herb that banishes all care, sorrow, and ill humour. -Whoever drinks wine thus drugged cannot shed a single tear all the rest -of the day, not even though his father and mother both of them drop -down dead, or he sees a brother or a son hewn in pieces before his very -eyes. This drug, of such sovereign power and virtue, had been given to -Helen by Polydamna wife of Thon, a woman of Egypt, where there grow all -sorts of herbs, some good to put into the mixing bowl and others -poisonous. Moreover, every one in the whole country is a skilled -physician, for they are of the race of Paeeon. When Helen had put this -drug in the bowl, and had told the servants to serve the wine round, -she said: - -“Menelaus, son of Atreus, and you my good friends, sons of honourable -men (which is as Jove wills, for he is the giver both of good and evil, -and can do what he chooses), feast here as you will, and listen while I -tell you a tale in season. I cannot indeed name every single one of the -exploits of Ulysses, but I can say what he did when he was before Troy, -and you Achaeans were in all sorts of difficulties. He covered himself -with wounds and bruises, dressed himself all in rags, and entered the -enemy’s city looking like a menial or a beggar, and quite different -from what he did when he was among his own people. In this disguise he -entered the city of Troy, and no one said anything to him. I alone -recognised him and began to question him, but he was too cunning for -me. When, however, I had washed and anointed him and had given him -clothes, and after I had sworn a solemn oath not to betray him to the -Trojans till he had got safely back to his own camp and to the ships, -he told me all that the Achaeans meant to do. He killed many Trojans -and got much information before he reached the Argive camp, for all -which things the Trojan women made lamentation, but for my own part I -was glad, for my heart was beginning to yearn after my home, and I was -unhappy about the wrong that Venus had done me in taking me over there, -away from my country, my girl, and my lawful wedded husband, who is -indeed by no means deficient either in person or understanding.” - -Then Menelaus said, “All that you have been saying, my dear wife, is -true. I have travelled much, and have had much to do with heroes, but I -have never seen such another man as Ulysses. What endurance too, and -what courage he displayed within the wooden horse, wherein all the -bravest of the Argives were lying in wait to bring death and -destruction upon the Trojans.43 At that moment you came up to us; some -god who wished well to the Trojans must have set you on to it and you -had Deiphobus with you. Three times did you go all round our hiding -place and pat it; you called our chiefs each by his own name, and -mimicked all our wives—Diomed, Ulysses, and I from our seats inside -heard what a noise you made. Diomed and I could not make up our minds -whether to spring out then and there, or to answer you from inside, but -Ulysses held us all in check, so we sat quite still, all except -Anticlus, who was beginning to answer you, when Ulysses clapped his two -brawny hands over his mouth, and kept them there. It was this that -saved us all, for he muzzled Anticlus till Minerva took you away -again.” - -“How sad,” exclaimed Telemachus, “that all this was of no avail to save -him, nor yet his own iron courage. But now, sir, be pleased to send us -all to bed, that we may lie down and enjoy the blessed boon of sleep.” - -On this Helen told the maid servants to set beds in the room that was -in the gatehouse, and to make them with good red rugs, and spread -coverlets on the top of them with woollen cloaks for the guests to -wear. So the maids went out, carrying a torch, and made the beds, to -which a man-servant presently conducted the strangers. Thus, then, did -Telemachus and Pisistratus sleep there in the forecourt, while the son -of Atreus lay in an inner room with lovely Helen by his side. - -When the child of morning, rosy-fingered Dawn appeared, Menelaus rose -and dressed himself. He bound his sandals on to his comely feet, girded -his sword about his shoulders, and left his room looking like an -immortal god. Then, taking a seat near Telemachus he said: - -“And what, Telemachus, has led you to take this long sea voyage to -Lacedaemon? Are you on public, or private business? Tell me all about -it.” - -“I have come, sir,” replied Telemachus, “to see if you can tell me -anything about my father. I am being eaten out of house and home; my -fair estate is being wasted, and my house is full of miscreants who -keep killing great numbers of my sheep and oxen, on the pretence of -paying their addresses to my mother. Therefore, I am suppliant at your -knees if haply you may tell me about my father’s melancholy end, -whether you saw it with your own eyes, or heard it from some other -traveller; for he was a man born to trouble. Do not soften things out -of any pity for myself, but tell me in all plainness exactly what you -saw. If my brave father Ulysses ever did you loyal service either by -word or deed, when you Achaeans were harassed by the Trojans, bear it -in mind now as in my favour and tell me truly all.” - -Menelaus on hearing this was very much shocked. “So,” he exclaimed, -“these cowards would usurp a brave man’s bed? A hind might as well lay -her new born young in the lair of a lion, and then go off to feed in -the forest or in some grassy dell: the lion when he comes back to his -lair will make short work with the pair of them—and so will Ulysses -with these suitors. By father Jove, Minerva, and Apollo, if Ulysses is -still the man that he was when he wrestled with Philomeleides in -Lesbos, and threw him so heavily that all the Achaeans cheered him—if -he is still such and were to come near these suitors, they would have a -short shrift and a sorry wedding. As regards your questions, however, I -will not prevaricate nor deceive you, but will tell you without -concealment all that the old man of the sea told me. - -“I was trying to come on here, but the gods detained me in Egypt, for -my hecatombs had not given them full satisfaction, and the gods are -very strict about having their dues. Now off Egypt, about as far as a -ship can sail in a day with a good stiff breeze behind her, there is an -island called Pharos—it has a good harbour from which vessels can get -out into open sea when they have taken in water—and here the gods -becalmed me twenty days without so much as a breath of fair wind to -help me forward. We should have run clean out of provisions and my men -would have starved, if a goddess had not taken pity upon me and saved -me in the person of Idothea, daughter to Proteus, the old man of the -sea, for she had taken a great fancy to me. - -“She came to me one day when I was by myself, as I often was, for the -men used to go with their barbed hooks, all over the island in the hope -of catching a fish or two to save them from the pangs of hunger. -‘Stranger,’ said she, ‘it seems to me that you like starving in this -way—at any rate it does not greatly trouble you, for you stick here day -after day, without even trying to get away though your men are dying by -inches.’ - -“‘Let me tell you,’ said I, ‘whichever of the goddesses you may happen -to be, that I am not staying here of my own accord, but must have -offended the gods that live in heaven. Tell me, therefore, for the gods -know everything, which of the immortals it is that is hindering me in -this way, and tell me also how I may sail the sea so as to reach my -home.’ - -“‘Stranger,’ replied she, ‘I will make it all quite clear to you. There -is an old immortal who lives under the sea hereabouts and whose name is -Proteus. He is an Egyptian, and people say he is my father; he is -Neptune’s head man and knows every inch of ground all over the bottom -of the sea. If you can snare him and hold him tight, he will tell you -about your voyage, what courses you are to take, and how you are to -sail the sea so as to reach your home. He will also tell you, if you so -will, all that has been going on at your house both good and bad, while -you have been away on your long and dangerous journey.’ - -“‘Can you show me,’ said I, ‘some stratagem by means of which I may -catch this old god without his suspecting it and finding me out? For a -god is not easily caught—not by a mortal man.’ - -“‘Stranger,’ said she, ‘I will make it all quite clear to you. About -the time when the sun shall have reached mid heaven, the old man of the -sea comes up from under the waves, heralded by the West wind that furs -the water over his head. As soon as he has come up he lies down, and -goes to sleep in a great sea cave, where the seals—Halosydne’s chickens -as they call them—come up also from the grey sea, and go to sleep in -shoals all round him; and a very strong and fish-like smell do they -bring with them. 44 Early to-morrow morning I will take you to this -place and will lay you in ambush. Pick out, therefore, the three best -men you have in your fleet, and I will tell you all the tricks that the -old man will play you. - -“‘First he will look over all his seals, and count them; then, when he -has seen them and tallied them on his five fingers, he will go to sleep -among them, as a shepherd among his sheep. The moment you see that he -is asleep seize him; put forth all your strength and hold him fast, for -he will do his very utmost to get away from you. He will turn himself -into every kind of creature that goes upon the earth, and will become -also both fire and water; but you must hold him fast and grip him -tighter and tighter, till he begins to talk to you and comes back to -what he was when you saw him go to sleep; then you may slacken your -hold and let him go; and you can ask him which of the gods it is that -is angry with you, and what you must do to reach your home over the -seas.’ - -“Having so said she dived under the waves, whereon I turned back to the -place where my ships were ranged upon the shore; and my heart was -clouded with care as I went along. When I reached my ship we got supper -ready, for night was falling, and camped down upon the beach. - -“When the child of morning rosy-fingered Dawn appeared, I took the -three men on whose prowess of all kinds I could most rely, and went -along by the sea-side, praying heartily to heaven. Meanwhile the -goddess fetched me up four seal skins from the bottom of the sea, all -of them just skinned, for she meant playing a trick upon her father. -Then she dug four pits for us to lie in, and sat down to wait till we -should come up. When we were close to her, she made us lie down in the -pits one after the other, and threw a seal skin over each of us. Our -ambuscade would have been intolerable, for the stench of the fishy -seals was most distressing45—who would go to bed with a sea monster if -he could help it?—but here, too, the goddess helped us, and thought of -something that gave us great relief, for she put some ambrosia under -each man’s nostrils, which was so fragrant that it killed the smell of -the seals.46 - -“We waited the whole morning and made the best of it, watching the -seals come up in hundreds to bask upon the sea shore, till at noon the -old man of the sea came up too, and when he had found his fat seals he -went over them and counted them. We were among the first he counted, -and he never suspected any guile, but laid himself down to sleep as -soon as he had done counting. Then we rushed upon him with a shout and -seized him; on which he began at once with his old tricks, and changed -himself first into a lion with a great mane; then all of a sudden he -became a dragon, a leopard, a wild boar; the next moment he was running -water, and then again directly he was a tree, but we stuck to him and -never lost hold, till at last the cunning old creature became -distressed, and said, ‘Which of the gods was it, Son of Atreus, that -hatched this plot with you for snaring me and seizing me against my -will? What do you want?’ - -“‘You know that yourself, old man,’ I answered, ‘you will gain nothing -by trying to put me off. It is because I have been kept so long in this -island, and see no sign of my being able to get away. I am losing all -heart; tell me, then, for you gods know everything, which of the -immortals it is that is hindering me, and tell me also how I may sail -the sea so as to reach my home?’ - -“Then,’ he said, ‘if you would finish your voyage and get home quickly, -you must offer sacrifices to Jove and to the rest of the gods before -embarking; for it is decreed that you shall not get back to your -friends, and to your own house, till you have returned to the -heaven-fed stream of Egypt, and offered holy hecatombs to the immortal -gods that reign in heaven. When you have done this they will let you -finish your voyage.’ - -“I was broken hearted when I heard that I must go back all that long -and terrible voyage to Egypt;47 nevertheless, I answered, ‘I will do -all, old man, that you have laid upon me; but now tell me, and tell me -true, whether all the Achaeans whom Nestor and I left behind us when we -set sail from Troy have got home safely, or whether any one of them -came to a bad end either on board his own ship or among his friends -when the days of his fighting were done.’ - -“‘Son of Atreus,’ he answered, ‘why ask me? You had better not know -what I can tell you, for your eyes will surely fill when you have heard -my story. Many of those about whom you ask are dead and gone, but many -still remain, and only two of the chief men among the Achaeans perished -during their return home. As for what happened on the field of -battle—you were there yourself. A third Achaean leader is still at sea, -alive, but hindered from returning. Ajax was wrecked, for Neptune drove -him on to the great rocks of Gyrae; nevertheless, he let him get safe -out of the water, and in spite of all Minerva’s hatred he would have -escaped death, if he had not ruined himself by boasting. He said the -gods could not drown him even though they had tried to do so, and when -Neptune heard this large talk, he seized his trident in his two brawny -hands, and split the rock of Gyrae in two pieces. The base remained -where it was, but the part on which Ajax was sitting fell headlong into -the sea and carried Ajax with it; so he drank salt water and was -drowned. - -“‘Your brother and his ships escaped, for Juno protected him, but when -he was just about to reach the high promontory of Malea, he was caught -by a heavy gale which carried him out to sea again sorely against his -will, and drove him to the foreland where Thyestes used to dwell, but -where Aegisthus was then living. By and by, however, it seemed as -though he was to return safely after all, for the gods backed the wind -into its old quarter and they reached home; whereon Agamemnon kissed -his native soil, and shed tears of joy at finding himself in his own -country. - -“‘Now there was a watchman whom Aegisthus kept always on the watch, and -to whom he had promised two talents of gold. This man had been looking -out for a whole year to make sure that Agamemnon did not give him the -slip and prepare war; when, therefore, this man saw Agamemnon go by, he -went and told Aegisthus, who at once began to lay a plot for him. He -picked twenty of his bravest warriors and placed them in ambuscade on -one side the cloister, while on the opposite side he prepared a -banquet. Then he sent his chariots and horsemen to Agamemnon, and -invited him to the feast, but he meant foul play. He got him there, all -unsuspicious of the doom that was awaiting him, and killed him when the -banquet was over as though he were butchering an ox in the shambles; -not one of Agamemnon’s followers was left alive, nor yet one of -Aegisthus’, but they were all killed there in the cloisters.’ - -“Thus spoke Proteus, and I was broken hearted as I heard him. I sat -down upon the sands and wept; I felt as though I could no longer bear -to live nor look upon the light of the sun. Presently, when I had had -my fill of weeping and writhing upon the ground, the old man of the sea -said, ‘Son of Atreus, do not waste any more time in crying so bitterly; -it can do no manner of good; find your way home as fast as ever you -can, for Aegisthus may be still alive, and even though Orestes has been -beforehand with you in killing him, you may yet come in for his -funeral.’ - -“On this I took comfort in spite of all my sorrow, and said, ‘I know, -then, about these two; tell me, therefore, about the third man of whom -you spoke; is he still alive, but at sea, and unable to get home? or is -he dead? Tell me, no matter how much it may grieve me.’ - -“‘The third man,’ he answered, ‘is Ulysses who dwells in Ithaca. I can -see him in an island sorrowing bitterly in the house of the nymph -Calypso, who is keeping him prisoner, and he cannot reach his home for -he has no ships nor sailors to take him over the sea. As for your own -end, Menelaus, you shall not die in Argos, but the gods will take you -to the Elysian plain, which is at the ends of the world. There -fair-haired Rhadamanthus reigns, and men lead an easier life than any -where else in the world, for in Elysium there falls not rain, nor hail, -nor snow, but Oceanus breathes ever with a West wind that sings softly -from the sea, and gives fresh life to all men. This will happen to you -because you have married Helen, and are Jove’s son-in-law.’ - -“As he spoke he dived under the waves, whereon I turned back to the -ships with my companions, and my heart was clouded with care as I went -along. When we reached the ships we got supper ready, for night was -falling, and camped down upon the beach. When the child of morning, -rosy-fingered Dawn appeared, we drew our ships into the water, and put -our masts and sails within them; then we went on board ourselves, took -our seats on the benches, and smote the grey sea with our oars. I again -stationed my ships in the heaven-fed stream of Egypt, and offered -hecatombs that were full and sufficient. When I had thus appeased -heaven’s anger, I raised a barrow to the memory of Agamemnon that his -name might live for ever, after which I had a quick passage home, for -the gods sent me a fair wind. - -“And now for yourself—stay here some ten or twelve days longer, and I -will then speed you on your way. I will make you a noble present of a -chariot and three horses. I will also give you a beautiful chalice that -so long as you live you may think of me whenever you make a -drink-offering to the immortal gods.” - -“Son of Atreus,” replied Telemachus, “do not press me to stay longer; I -should be contented to remain with you for another twelve months; I -find your conversation so delightful that I should never once wish -myself at home with my parents; but my crew whom I have left at Pylos -are already impatient, and you are detaining me from them. As for any -present you may be disposed to make me, I had rather that it should be -a piece of plate. I will take no horses back with me to Ithaca, but -will leave them to adorn your own stables, for you have much flat -ground in your kingdom where lotus thrives, as also meadow-sweet and -wheat and barley, and oats with their white and spreading ears; whereas -in Ithaca we have neither open fields nor racecourses, and the country -is more fit for goats than horses, and I like it the better for that. -48 None of our islands have much level ground, suitable for horses, and -Ithaca least of all.” - -Menelaus smiled and took Telemachus’s hand within his own. “What you -say,” said he, “shows that you come of good family. I both can, and -will, make this exchange for you, by giving you the finest and most -precious piece of plate in all my house. It is a mixing bowl by -Vulcan’s own hand, of pure silver, except the rim, which is inlaid with -gold. Phaedimus, king of the Sidonians, gave it me in the course of a -visit which I paid him when I returned thither on my homeward journey. -I will make you a present of it.” - -Thus did they converse [and guests kept coming to the king’s house. -They brought sheep and wine, while their wives had put up bread for -them to take with them; so they were busy cooking their dinners in the -courts].49 - -Meanwhile the suitors were throwing discs or aiming with spears at a -mark on the levelled ground in front of Ulysses’ house, and were -behaving with all their old insolence. Antinous and Eurymachus, who -were their ringleaders and much the foremost among them all, were -sitting together when Noemon son of Phronius came up and said to -Antinous, - -“Have we any idea, Antinous, on what day Telemachus returns from Pylos? -He has a ship of mine, and I want it, to cross over to Elis: I have -twelve brood mares there with yearling mule foals by their side not yet -broken in, and I want to bring one of them over here and break him.” - -They were astounded when they heard this, for they had made sure that -Telemachus had not gone to the city of Neleus. They thought he was only -away somewhere on the farms, and was with the sheep, or with the -swineherd; so Antinous said, “When did he go? Tell me truly, and what -young men did he take with him? Were they freemen or his own -bondsmen—for he might manage that too? Tell me also, did you let him -have the ship of your own free will because he asked you, or did he -take it without your leave?” - -“I lent it him,” answered Noemon, “what else could I do when a man of -his position said he was in a difficulty, and asked me to oblige him? I -could not possibly refuse. As for those who went with him they were the -best young men we have, and I saw Mentor go on board as captain—or some -god who was exactly like him. I cannot understand it, for I saw Mentor -here myself yesterday morning, and yet he was then setting out for -Pylos.” - -Noemon then went back to his father’s house, but Antinous and -Eurymachus were very angry. They told the others to leave off playing, -and to come and sit down along with themselves. When they came, -Antinous son of Eupeithes spoke in anger. His heart was black with -rage, and his eyes flashed fire as he said: - -“Good heavens, this voyage of Telemachus is a very serious matter; we -had made sure that it would come to nothing, but the young fellow has -got away in spite of us, and with a picked crew too. He will be giving -us trouble presently; may Jove take him before he is full grown. Find -me a ship, therefore, with a crew of twenty men, and I will lie in wait -for him in the straits between Ithaca and Samos; he will then rue the -day that he set out to try and get news of his father.” - -Thus did he speak, and the others applauded his saying; they then all -of them went inside the buildings. - -It was not long ere Penelope came to know what the suitors were -plotting; for a man servant, Medon, overheard them from outside the -outer court as they were laying their schemes within, and went to tell -his mistress. As he crossed the threshold of her room Penelope said: -“Medon, what have the suitors sent you here for? Is it to tell the -maids to leave their master’s business and cook dinner for them? I wish -they may neither woo nor dine henceforward, neither here nor anywhere -else, but let this be the very last time, for the waste you all make of -my son’s estate. Did not your fathers tell you when you were children, -how good Ulysses had been to them—never doing anything high-handed, nor -speaking harshly to anybody? Kings may say things sometimes, and they -may take a fancy to one man and dislike another, but Ulysses never did -an unjust thing by anybody—which shows what bad hearts you have, and -that there is no such thing as gratitude left in this world.” - -Then Medon said, “I wish, Madam, that this were all; but they are -plotting something much more dreadful now—may heaven frustrate their -design. They are going to try and murder Telemachus as he is coming -home from Pylos and Lacedaemon, where he has been to get news of his -father.” - -Then Penelope’s heart sank within her, and for a long time she was -speechless; her eyes filled with tears, and she could find no -utterance. At last, however, she said, “Why did my son leave me? What -business had he to go sailing off in ships that make long voyages over -the ocean like sea-horses? Does he want to die without leaving any one -behind him to keep up his name?” - -“I do not know,” answered Medon, “whether some god set him on to it, or -whether he went on his own impulse to see if he could find out if his -father was dead, or alive and on his way home.” - -Then he went downstairs again, leaving Penelope in an agony of grief. -There were plenty of seats in the house, but she had no heart for -sitting on any one of them; she could only fling herself on the floor -of her own room and cry; whereon all the maids in the house, both old -and young, gathered round her and began to cry too, till at last in a -transport of sorrow she exclaimed, - -“My dears, heaven has been pleased to try me with more affliction than -any other woman of my age and country. First I lost my brave and -lion-hearted husband, who had every good quality under heaven, and -whose name was great over all Hellas and middle Argos, and now my -darling son is at the mercy of the winds and waves, without my having -heard one word about his leaving home. You hussies, there was not one -of you would so much as think of giving me a call out of my bed, though -you all of you very well knew when he was starting. If I had known he -meant taking this voyage, he would have had to give it up, no matter -how much he was bent upon it, or leave me a corpse behind him—one or -other. Now, however, go some of you and call old Dolius, who was given -me by my father on my marriage, and who is my gardener. Bid him go at -once and tell everything to Laertes, who may be able to hit on some -plan for enlisting public sympathy on our side, as against those who -are trying to exterminate his own race and that of Ulysses.” - -Then the dear old nurse Euryclea said, “You may kill me, Madam, or let -me live on in your house, whichever you please, but I will tell you the -real truth. I knew all about it, and gave him everything he wanted in -the way of bread and wine, but he made me take my solemn oath that I -would not tell you anything for some ten or twelve days, unless you -asked or happened to hear of his having gone, for he did not want you -to spoil your beauty by crying. And now, Madam, wash your face, change -your dress, and go upstairs with your maids to offer prayers to -Minerva, daughter of Aegis-bearing Jove, for she can save him even -though he be in the jaws of death. Do not trouble Laertes: he has -trouble enough already. Besides, I cannot think that the gods hate the -race of the son of Arceisius so much, but there will be a son left to -come up after him, and inherit both the house and the fair fields that -lie far all round it.” - -With these words she made her mistress leave off crying, and dried the -tears from her eyes. Penelope washed her face, changed her dress, and -went upstairs with her maids. She then put some bruised barley into a -basket and began praying to Minerva. - -“Hear me,” she cried, “Daughter of Aegis-bearing Jove, unweariable. If -ever Ulysses while he was here burned you fat thigh bones of sheep or -heifer, bear it in mind now as in my favour, and save my darling son -from the villainy of the suitors.” - -She cried aloud as she spoke, and the goddess heard her prayer; -meanwhile the suitors were clamorous throughout the covered cloister, -and one of them said: - -“The queen is preparing for her marriage with one or other of us. -Little does she dream that her son has now been doomed to die.” - -This was what they said, but they did not know what was going to -happen. Then Antinous said, “Comrades, let there be no loud talking, -lest some of it get carried inside. Let us be up and do that in -silence, about which we are all of a mind.” - -He then chose twenty men, and they went down to their ship and to the -sea side; they drew the vessel into the water and got her mast and -sails inside her; they bound the oars to the thole-pins with twisted -thongs of leather, all in due course, and spread the white sails aloft, -while their fine servants brought them their armour. Then they made the -ship fast a little way out, came on shore again, got their suppers, and -waited till night should fall. - -But Penelope lay in her own room upstairs unable to eat or drink, and -wondering whether her brave son would escape, or be overpowered by the -wicked suitors. Like a lioness caught in the toils with huntsmen -hemming her in on every side she thought and thought till she sank into -a slumber, and lay on her bed bereft of thought and motion. - -Then Minerva bethought her of another matter, and made a vision in the -likeness of Penelope’s sister Iphthime daughter of Icarius who had -married Eumelus and lived in Pherae. She told the vision to go to the -house of Ulysses, and to make Penelope leave off crying, so it came -into her room by the hole through which the thong went for pulling the -door to, and hovered over her head saying, - -“You are asleep, Penelope: the gods who live at ease will not suffer -you to weep and be so sad. Your son has done them no wrong, so he will -yet come back to you.” - -Penelope, who was sleeping sweetly at the gates of dreamland, answered, -“Sister, why have you come here? You do not come very often, but I -suppose that is because you live such a long way off. Am I, then, to -leave off crying and refrain from all the sad thoughts that torture me? -I, who have lost my brave and lion-hearted husband, who had every good -quality under heaven, and whose name was great over all Hellas and -middle Argos; and now my darling son has gone off on board of a ship—a -foolish fellow who has never been used to roughing it, nor to going -about among gatherings of men. I am even more anxious about him than -about my husband; I am all in a tremble when I think of him, lest -something should happen to him, either from the people among whom he -has gone, or by sea, for he has many enemies who are plotting against -him, and are bent on killing him before he can return home.” - -Then the vision said, “Take heart, and be not so much dismayed. There -is one gone with him whom many a man would be glad enough to have stand -by his side, I mean Minerva; it is she who has compassion upon you, and -who has sent me to bear you this message.” - -“Then,” said Penelope, “if you are a god or have been sent here by -divine commission, tell me also about that other unhappy one—is he -still alive, or is he already dead and in the house of Hades?” - -And the vision said, “I shall not tell you for certain whether he is -alive or dead, and there is no use in idle conversation.” - -Then it vanished through the thong-hole of the door and was dissipated -into thin air; but Penelope rose from her sleep refreshed and -comforted, so vivid had been her dream. - -Meantime the suitors went on board and sailed their ways over the sea, -intent on murdering Telemachus. Now there is a rocky islet called -Asteris, of no great size, in mid channel between Ithaca and Samos, and -there is a harbour on either side of it where a ship can lie. Here then -the Achaeans placed themselves in ambush. - - - - -BOOK V - - -CALYPSO—ULYSSES REACHES SCHERIA ON A RAFT. - - -And now, as Dawn rose from her couch beside Tithonus—harbinger of light -alike to mortals and immortals—the gods met in council and with them, -Jove the lord of thunder, who is their king. Thereon Minerva began to -tell them of the many sufferings of Ulysses, for she pitied him away -there in the house of the nymph Calypso. - -“Father Jove,” said she, “and all you other gods that live in -everlasting bliss, I hope there may never be such a thing as a kind and -well-disposed ruler any more, nor one who will govern equitably. I hope -they will be all henceforth cruel and unjust, for there is not one of -his subjects but has forgotten Ulysses, who ruled them as though he -were their father. There he is, lying in great pain in an island where -dwells the nymph Calypso, who will not let him go; and he cannot get -back to his own country, for he can find neither ships nor sailors to -take him over the sea. Furthermore, wicked people are now trying to -murder his only son Telemachus, who is coming home from Pylos and -Lacedaemon, where he has been to see if he can get news of his father.” - -“What, my dear, are you talking about?” replied her father, “did you -not send him there yourself, because you thought it would help Ulysses -to get home and punish the suitors? Besides, you are perfectly able to -protect Telemachus, and to see him safely home again, while the suitors -have to come hurry-skurrying back without having killed him.” - -When he had thus spoken, he said to his son Mercury, “Mercury, you are -our messenger, go therefore and tell Calypso we have decreed that poor -Ulysses is to return home. He is to be convoyed neither by gods nor -men, but after a perilous voyage of twenty days upon a raft he is to -reach fertile Scheria,50 the land of the Phaeacians, who are near of -kin to the gods, and will honour him as though he were one of -ourselves. They will send him in a ship to his own country, and will -give him more bronze and gold and raiment than he would have brought -back from Troy, if he had had all his prize money and had got home -without disaster. This is how we have settled that he shall return to -his country and his friends.” - -Thus he spoke, and Mercury, guide and guardian, slayer of Argus, did as -he was told. Forthwith he bound on his glittering golden sandals with -which he could fly like the wind over land and sea. He took the wand -with which he seals men’s eyes in sleep or wakes them just as he -pleases, and flew holding it in his hand over Pieria; then he swooped -down through the firmament till he reached the level of the sea, whose -waves he skimmed like a cormorant that flies fishing every hole and -corner of the ocean, and drenching its thick plumage in the spray. He -flew and flew over many a weary wave, but when at last he got to the -island which was his journey’s end, he left the sea and went on by land -till he came to the cave where the nymph Calypso lived. - -He found her at home. There was a large fire burning on the hearth, and -one could smell from far the fragrant reek of burning cedar and sandal -wood. As for herself, she was busy at her loom, shooting her golden -shuttle through the warp and singing beautifully. Round her cave there -was a thick wood of alder, poplar, and sweet smelling cypress trees, -wherein all kinds of great birds had built their nests—owls, hawks, and -chattering sea-crows that occupy their business in the waters. A vine -loaded with grapes was trained and grew luxuriantly about the mouth of -the cave; there were also four running rills of water in channels cut -pretty close together, and turned hither and thither so as to irrigate -the beds of violets and luscious herbage over which they flowed. 51 -Even a god could not help being charmed with such a lovely spot, so -Mercury stood still and looked at it; but when he had admired it -sufficiently he went inside the cave. - -Calypso knew him at once—for the gods all know each other, no matter -how far they live from one another—but Ulysses was not within; he was -on the sea-shore as usual, looking out upon the barren ocean with tears -in his eyes, groaning and breaking his heart for sorrow. Calypso gave -Mercury a seat and said: “Why have you come to see me, -Mercury—honoured, and ever welcome—for you do not visit me often? Say -what you want; I will do it for you at once if I can, and if it can be -done at all; but come inside, and let me set refreshment before you.” - -As she spoke she drew a table loaded with ambrosia beside him and mixed -him some red nectar, so Mercury ate and drank till he had had enough, -and then said: - -“We are speaking god and goddess to one another, and you ask me why I -have come here, and I will tell you truly as you would have me do. Jove -sent me; it was no doing of mine; who could possibly want to come all -this way over the sea where there are no cities full of people to offer -me sacrifices or choice hecatombs? Nevertheless I had to come, for none -of us other gods can cross Jove, nor transgress his orders. He says -that you have here the most ill-starred of all those who fought nine -years before the city of King Priam and sailed home in the tenth year -after having sacked it. On their way home they sinned against -Minerva,52 who raised both wind and waves against them, so that all his -brave companions perished, and he alone was carried hither by wind and -tide. Jove says that you are to let this man go at once, for it is -decreed that he shall not perish here, far from his own people, but -shall return to his house and country and see his friends again.” - -Calypso trembled with rage when she heard this, “You gods,” she -exclaimed, “ought to be ashamed of yourselves. You are always jealous -and hate seeing a goddess take a fancy to a mortal man, and live with -him in open matrimony. So when rosy-fingered Dawn made love to Orion, -you precious gods were all of you furious till Diana went and killed -him in Ortygia. So again when Ceres fell in love with Iasion, and -yielded to him in a thrice-ploughed fallow field, Jove came to hear of -it before so very long and killed Iasion with his thunderbolts. And now -you are angry with me too because I have a man here. I found the poor -creature sitting all alone astride of a keel, for Jove had struck his -ship with lightning and sunk it in mid ocean, so that all his crew were -drowned, while he himself was driven by wind and waves on to my island. -I got fond of him and cherished him, and had set my heart on making him -immortal, so that he should never grow old all his days; still I cannot -cross Jove, nor bring his counsels to nothing; therefore, if he insists -upon it, let the man go beyond the seas again; but I cannot send him -anywhere myself for I have neither ships nor men who can take him. -Nevertheless I will readily give him such advice, in all good faith, as -will be likely to bring him safely to his own country.” - -“Then send him away,” said Mercury, “or Jove will be angry with you and -punish you”. - -On this he took his leave, and Calypso went out to look for Ulysses, -for she had heard Jove’s message. She found him sitting upon the beach -with his eyes ever filled with tears, and dying of sheer home sickness; -for he had got tired of Calypso, and though he was forced to sleep with -her in the cave by night, it was she, not he, that would have it so. As -for the day time, he spent it on the rocks and on the sea shore, -weeping, crying aloud for his despair, and always looking out upon the -sea. Calypso then went close up to him said: - -“My poor fellow, you shall not stay here grieving and fretting your -life out any longer. I am going to send you away of my own free will; -so go, cut some beams of wood, and make yourself a large raft with an -upper deck that it may carry you safely over the sea. I will put bread, -wine, and water on board to save you from starving. I will also give -you clothes, and will send you a fair wind to take you home, if the -gods in heaven so will it—for they know more about these things, and -can settle them better than I can.” - -Ulysses shuddered as he heard her. “Now goddess,” he answered, “there -is something behind all this; you cannot be really meaning to help me -home when you bid me do such a dreadful thing as put to sea on a raft. -Not even a well found ship with a fair wind could venture on such a -distant voyage: nothing that you can say or do shall make me go on -board a raft unless you first solemnly swear that you mean me no -mischief.” - -Calypso smiled at this and caressed him with her hand: “You know a -great deal,” said she, “but you are quite wrong here. May heaven above -and earth below be my witnesses, with the waters of the river Styx—and -this is the most solemn oath which a blessed god can take—that I mean -you no sort of harm, and am only advising you to do exactly what I -should do myself in your place. I am dealing with you quite -straightforwardly; my heart is not made of iron, and I am very sorry -for you.” - -When she had thus spoken she led the way rapidly before him, and -Ulysses followed in her steps; so the pair, goddess and man, went on -and on till they came to Calypso’s cave, where Ulysses took the seat -that Mercury had just left. Calypso set meat and drink before him of -the food that mortals eat; but her maids brought ambrosia and nectar -for herself, and they laid their hands on the good things that were -before them. When they had satisfied themselves with meat and drink, -Calypso spoke, saying: - -“Ulysses, noble son of Laertes, so you would start home to your own -land at once? Good luck go with you, but if you could only know how -much suffering is in store for you before you get back to your own -country, you would stay where you are, keep house along with me, and -let me make you immortal, no matter how anxious you may be to see this -wife of yours, of whom you are thinking all the time day after day; yet -I flatter myself that I am no whit less tall or well-looking than she -is, for it is not to be expected that a mortal woman should compare in -beauty with an immortal.” - -“Goddess,” replied Ulysses, “do not be angry with me about this. I am -quite aware that my wife Penelope is nothing like so tall or so -beautiful as yourself. She is only a woman, whereas you are an -immortal. Nevertheless, I want to get home, and can think of nothing -else. If some god wrecks me when I am on the sea, I will bear it and -make the best of it. I have had infinite trouble both by land and sea -already, so let this go with the rest.” - -Presently the sun set and it became dark, whereon the pair retired into -the inner part of the cave and went to bed. - -When the child of morning rosy-fingered Dawn appeared, Ulysses put on -his shirt and cloak, while the goddess wore a dress of a light gossamer -fabric, very fine and graceful, with a beautiful golden girdle about -her waist and a veil to cover her head. She at once set herself to -think how she could speed Ulysses on his way. So she gave him a great -bronze axe that suited his hands; it was sharpened on both sides, and -had a beautiful olive-wood handle fitted firmly on to it. She also gave -him a sharp adze, and then led the way to the far end of the island -where the largest trees grew—alder, poplar and pine, that reached the -sky—very dry and well seasoned, so as to sail light for him in the -water.53 Then, when she had shown him where the best trees grew, -Calypso went home, leaving him to cut them, which he soon finished -doing. He cut down twenty trees in all and adzed them smooth, squaring -them by rule in good workmanlike fashion. Meanwhile Calypso came back -with some augers, so he bored holes with them and fitted the timbers -together with bolts and rivets. He made the raft as broad as a skilled -shipwright makes the beam of a large vessel, and he fixed a deck on top -of the ribs, and ran a gunwale all round it. He also made a mast with a -yard arm, and a rudder to steer with. He fenced the raft all round with -wicker hurdles as a protection against the waves, and then he threw on -a quantity of wood. By and by Calypso brought him some linen to make -the sails, and he made these too, excellently, making them fast with -braces and sheets. Last of all, with the help of levers, he drew the -raft down into the water. - -In four days he had completed the whole work, and on the fifth Calypso -sent him from the island after washing him and giving him some clean -clothes. She gave him a goat skin full of black wine, and another -larger one of water; she also gave him a wallet full of provisions, and -found him in much good meat. Moreover, she made the wind fair and warm -for him, and gladly did Ulysses spread his sail before it, while he sat -and guided the raft skilfully by means of the rudder. He never closed -his eyes, but kept them fixed on the Pleiads, on late-setting Bootes, -and on the Bear—which men also call the wain, and which turns round and -round where it is, facing Orion, and alone never dipping into the -stream of Oceanus—for Calypso had told him to keep this to his left. -Days seven and ten did he sail over the sea, and on the eighteenth the -dim outlines of the mountains on the nearest part of the Phaeacian -coast appeared, rising like a shield on the horizon. - -But King Neptune, who was returning from the Ethiopians, caught sight -of Ulysses a long way off, from the mountains of the Solymi. He could -see him sailing upon the sea, and it made him very angry, so he wagged -his head and muttered to himself, saying, “Good heavens, so the gods -have been changing their minds about Ulysses while I was away in -Ethiopia, and now he is close to the land of the Phaeacians, where it -is decreed that he shall escape from the calamities that have befallen -him. Still, he shall have plenty of hardship yet before he has done -with it.” - -Thereon he gathered his clouds together, grasped his trident, stirred -it round in the sea, and roused the rage of every wind that blows till -earth, sea, and sky were hidden in cloud, and night sprang forth out of -the heavens. Winds from East, South, North, and West fell upon him all -at the same time, and a tremendous sea got up, so that Ulysses’ heart -began to fail him. “Alas,” he said to himself in his dismay, “what ever -will become of me? I am afraid Calypso was right when she said I should -have trouble by sea before I got back home. It is all coming true. How -black is Jove making heaven with his clouds, and what a sea the winds -are raising from every quarter at once. I am now safe to perish. Blest -and thrice blest were those Danaans who fell before Troy in the cause -of the sons of Atreus. Would that I had been killed on the day when the -Trojans were pressing me so sorely about the dead body of Achilles, for -then I should have had due burial and the Achaeans would have honoured -my name; but now it seems that I shall come to a most pitiable end.” - -As he spoke a sea broke over him with such terrific fury that the raft -reeled again, and he was carried overboard a long way off. He let go -the helm, and the force of the hurricane was so great that it broke the -mast half way up, and both sail and yard went over into the sea. For a -long time Ulysses was under water, and it was all he could do to rise -to the surface again, for the clothes Calypso had given him weighed him -down; but at last he got his head above water and spat out the bitter -brine that was running down his face in streams. In spite of all this, -however, he did not lose sight of his raft, but swam as fast as he -could towards it, got hold of it, and climbed on board again so as to -escape drowning. The sea took the raft and tossed it about as Autumn -winds whirl thistledown round and round upon a road. It was as though -the South, North, East, and West winds were all playing battledore and -shuttlecock with it at once. - -When he was in this plight, Ino daughter of Cadmus, also called -Leucothea, saw him. She had formerly been a mere mortal, but had been -since raised to the rank of a marine goddess. Seeing in what great -distress Ulysses now was, she had compassion upon him, and, rising like -a sea-gull from the waves, took her seat upon the raft. - -“My poor good man,” said she, “why is Neptune so furiously angry with -you? He is giving you a great deal of trouble, but for all his bluster -he will not kill you. You seem to be a sensible person, do then as I -bid you; strip, leave your raft to drive before the wind, and swim to -the Phaeacian coast where better luck awaits you. And here, take my -veil and put it round your chest; it is enchanted, and you can come to -no harm so long as you wear it. As soon as you touch land take it off, -throw it back as far as you can into the sea, and then go away again.” -With these words she took off her veil and gave it him. Then she dived -down again like a sea-gull and vanished beneath the dark blue waters. - -But Ulysses did not know what to think. “Alas,” he said to himself in -his dismay, “this is only some one or other of the gods who is luring -me to ruin by advising me to quit my raft. At any rate I will not do so -at present, for the land where she said I should be quit of all -troubles seemed to be still a good way off. I know what I will do—I am -sure it will be best—no matter what happens I will stick to the raft as -long as her timbers hold together, but when the sea breaks her up I -will swim for it; I do not see how I can do any better than this.” - -While he was thus in two minds, Neptune sent a terrible great wave that -seemed to rear itself above his head till it broke right over the raft, -which then went to pieces as though it were a heap of dry chaff tossed -about by a whirlwind. Ulysses got astride of one plank and rode upon it -as if he were on horseback; he then took off the clothes Calypso had -given him, bound Ino’s veil under his arms, and plunged into the -sea—meaning to swim on shore. King Neptune watched him as he did so, -and wagged his head, muttering to himself and saying, “There now, swim -up and down as you best can till you fall in with well-to-do people. I -do not think you will be able to say that I have let you off too -lightly.” On this he lashed his horses and drove to Aegae where his -palace is. - -But Minerva resolved to help Ulysses, so she bound the ways of all the -winds except one, and made them lie quite still; but she roused a good -stiff breeze from the North that should lay the waters till Ulysses -reached the land of the Phaeacians where he would be safe. - -Thereon he floated about for two nights and two days in the water, with -a heavy swell on the sea and death staring him in the face; but when -the third day broke, the wind fell and there was a dead calm without so -much as a breath of air stirring. As he rose on the swell he looked -eagerly ahead, and could see land quite near. Then, as children rejoice -when their dear father begins to get better after having for a long -time borne sore affliction sent him by some angry spirit, but the gods -deliver him from evil, so was Ulysses thankful when he again saw land -and trees, and swam on with all his strength that he might once more -set foot upon dry ground. When, however, he got within earshot, he -began to hear the surf thundering up against the rocks, for the swell -still broke against them with a terrific roar. Everything was enveloped -in spray; there were no harbours where a ship might ride, nor shelter -of any kind, but only headlands, low-lying rocks, and mountain tops. - -Ulysses’ heart now began to fail him, and he said despairingly to -himself, “Alas, Jove has let me see land after swimming so far that I -had given up all hope, but I can find no landing place, for the coast -is rocky and surf-beaten, the rocks are smooth and rise sheer from the -sea, with deep water close under them so that I cannot climb out for -want of foot hold. I am afraid some great wave will lift me off my legs -and dash me against the rocks as I leave the water—which would give me -a sorry landing. If, on the other hand, I swim further in search of -some shelving beach or harbour, a hurricane may carry me out to sea -again sorely against my will, or heaven may send some great monster of -the deep to attack me; for Amphitrite breeds many such, and I know that -Neptune is very angry with me.” - -While he was thus in two minds a wave caught him and took him with such -force against the rocks that he would have been smashed and torn to -pieces if Minerva had not shown him what to do. He caught hold of the -rock with both hands and clung to it groaning with pain till the wave -retired, so he was saved that time; but presently the wave came on -again and carried him back with it far into the sea—tearing his hands -as the suckers of a polypus are torn when some one plucks it from its -bed, and the stones come up along with it—even so did the rocks tear -the skin from his strong hands, and then the wave drew him deep down -under the water. - -Here poor Ulysses would have certainly perished even in spite of his -own destiny, if Minerva had not helped him to keep his wits about him. -He swam seaward again, beyond reach of the surf that was beating -against the land, and at the same time he kept looking towards the -shore to see if he could find some haven, or a spit that should take -the waves aslant. By and by, as he swam on, he came to the mouth of a -river, and here he thought would be the best place, for there were no -rocks, and it afforded shelter from the wind. He felt that there was a -current, so he prayed inwardly and said: - -“Hear me, O King, whoever you may be, and save me from the anger of the -sea-god Neptune, for I approach you prayerfully. Any one who has lost -his way has at all times a claim even upon the gods, wherefore in my -distress I draw near to your stream, and cling to the knees of your -riverhood. Have mercy upon me, O king, for I declare myself your -suppliant.” - -Then the god staid his stream and stilled the waves, making all calm -before him, and bringing him safely into the mouth of the river. Here -at last Ulysses’ knees and strong hands failed him, for the sea had -completely broken him. His body was all swollen, and his mouth and -nostrils ran down like a river with sea-water, so that he could neither -breathe nor speak, and lay swooning from sheer exhaustion; presently, -when he had got his breath and came to himself again, he took off the -scarf that Ino had given him and threw it back into the salt54 stream -of the river, whereon Ino received it into her hands from the wave that -bore it towards her. Then he left the river, laid himself down among -the rushes, and kissed the bounteous earth. - -“Alas,” he cried to himself in his dismay, “what ever will become of -me, and how is it all to end? If I stay here upon the river bed through -the long watches of the night, I am so exhausted that the bitter cold -and damp may make an end of me—for towards sunrise there will be a keen -wind blowing from off the river. If, on the other hand, I climb the -hill side, find shelter in the woods, and sleep in some thicket, I may -escape the cold and have a good night’s rest, but some savage beast may -take advantage of me and devour me.” - -In the end he deemed it best to take to the woods, and he found one -upon some high ground not far from the water. There he crept beneath -two shoots of olive that grew from a single stock—the one an ungrafted -sucker, while the other had been grafted. No wind, however squally, -could break through the cover they afforded, nor could the sun’s rays -pierce them, nor the rain get through them, so closely did they grow -into one another. Ulysses crept under these and began to make himself a -bed to lie on, for there was a great litter of dead leaves lying -about—enough to make a covering for two or three men even in hard -winter weather. He was glad enough to see this, so he laid himself down -and heaped the leaves all round him. Then, as one who lives alone in -the country, far from any neighbor, hides a brand as fire-seed in the -ashes to save himself from having to get a light elsewhere, even so did -Ulysses cover himself up with leaves; and Minerva shed a sweet sleep -upon his eyes, closed his eyelids, and made him lose all memories of -his sorrows. - - - - -BOOK VI - - -THE MEETING BETWEEN NAUSICAA AND ULYSSES. - - -So here Ulysses slept, overcome by sleep and toil; but Minerva went off -to the country and city of the Phaeacians—a people who used to live in -the fair town of Hypereia, near the lawless Cyclopes. Now the Cyclopes -were stronger than they and plundered them, so their king Nausithous -moved them thence and settled them in Scheria, far from all other -people. He surrounded the city with a wall, built houses and temples, -and divided the lands among his people; but he was dead and gone to the -house of Hades, and King Alcinous, whose counsels were inspired of -heaven, was now reigning. To his house, then, did Minerva hie in -furtherance of the return of Ulysses. - -She went straight to the beautifully decorated bedroom in which there -slept a girl who was as lovely as a goddess, Nausicaa, daughter to King -Alcinous. Two maid servants were sleeping near her, both very pretty, -one on either side of the doorway, which was closed with well made -folding doors. Minerva took the form of the famous sea captain Dymas’s -daughter, who was a bosom friend of Nausicaa and just her own age; -then, coming up to the girl’s bedside like a breath of wind, she -hovered over her head and said: - -“Nausicaa, what can your mother have been about, to have such a lazy -daughter? Here are your clothes all lying in disorder, yet you are -going to be married almost immediately, and should not only be well -dressed yourself, but should find good clothes for those who attend -you. This is the way to get yourself a good name, and to make your -father and mother proud of you. Suppose, then, that we make tomorrow a -washing day, and start at daybreak. I will come and help you so that -you may have everything ready as soon as possible, for all the best -young men among your own people are courting you, and you are not going -to remain a maid much longer. Ask your father, therefore, to have a -waggon and mules ready for us at daybreak, to take the rugs, robes, and -girdles, and you can ride, too, which will be much pleasanter for you -than walking, for the washing-cisterns are some way from the town.” - -When she had said this Minerva went away to Olympus, which they say is -the everlasting home of the gods. Here no wind beats roughly, and -neither rain nor snow can fall; but it abides in everlasting sunshine -and in a great peacefulness of light, wherein the blessed gods are -illumined for ever and ever. This was the place to which the goddess -went when she had given instructions to the girl. - -By and by morning came and woke Nausicaa, who began wondering about her -dream; she therefore went to the other end of the house to tell her -father and mother all about it, and found them in their own room. Her -mother was sitting by the fireside spinning her purple yarn with her -maids around her, and she happened to catch her father just as he was -going out to attend a meeting of the town council, which the Phaeacian -aldermen had convened. She stopped him and said: - -“Papa dear, could you manage to let me have a good big waggon? I want -to take all our dirty clothes to the river and wash them. You are the -chief man here, so it is only right that you should have a clean shirt -when you attend meetings of the council. Moreover, you have five sons -at home, two of them married, while the other three are good looking -bachelors; you know they always like to have clean linen when they go -to a dance, and I have been thinking about all this.” - -She did not say a word about her own wedding, for she did not like to, -but her father knew and said, “You shall have the mules, my love, and -whatever else you have a mind for. Be off with you, and the men shall -get you a good strong waggon with a body to it that will hold all your -clothes.” - -On this he gave his orders to the servants, who got the waggon out, -harnessed the mules, and put them to, while the girl brought the -clothes down from the linen room and placed them on the waggon. Her -mother prepared her a basket of provisions with all sorts of good -things, and a goat skin full of wine; the girl now got into the waggon, -and her mother gave her also a golden cruse of oil, that she and her -women might anoint themselves. Then she took the whip and reins and -lashed the mules on, whereon they set off, and their hoofs clattered on -the road. They pulled without flagging, and carried not only Nausicaa -and her wash of clothes, but the maids also who were with her. - -When they reached the water side they went to the washing cisterns, -through which there ran at all times enough pure water to wash any -quantity of linen, no matter how dirty. Here they unharnessed the mules -and turned them out to feed on the sweet juicy herbage that grew by the -water side. They took the clothes out of the waggon, put them in the -water, and vied with one another in treading them in the pits to get -the dirt out. After they had washed them and got them quite clean, they -laid them out by the sea side, where the waves had raised a high beach -of shingle, and set about washing themselves and anointing themselves -with olive oil. Then they got their dinner by the side of the stream, -and waited for the sun to finish drying the clothes. When they had done -dinner they threw off the veils that covered their heads and began to -play at ball, while Nausicaa sang for them. As the huntress Diana goes -forth upon the mountains of Taygetus or Erymanthus to hunt wild boars -or deer, and the wood nymphs, daughters of Aegis-bearing Jove, take -their sport along with her (then is Leto proud at seeing her daughter -stand a full head taller than the others, and eclipse the loveliest -amid a whole bevy of beauties), even so did the girl outshine her -handmaids. - -When it was time for them to start home, and they were folding the -clothes and putting them into the waggon, Minerva began to consider how -Ulysses should wake up and see the handsome girl who was to conduct him -to the city of the Phaeacians. The girl, therefore, threw a ball at one -of the maids, which missed her and fell into deep water. On this they -all shouted, and the noise they made woke Ulysses, who sat up in his -bed of leaves and began to wonder what it might all be. - -“Alas,” said he to himself, “what kind of people have I come amongst? -Are they cruel, savage, and uncivilised, or hospitable and humane? I -seem to hear the voices of young women, and they sound like those of -the nymphs that haunt mountain tops, or springs of rivers and meadows -of green grass. At any rate I am among a race of men and women. Let me -try if I cannot manage to get a look at them.” - -As he said this he crept from under his bush, and broke off a bough -covered with thick leaves to hide his nakedness. He looked like some -lion of the wilderness that stalks about exulting in his strength and -defying both wind and rain; his eyes glare as he prowls in quest of -oxen, sheep, or deer, for he is famished, and will dare break even into -a well fenced homestead, trying to get at the sheep—even such did -Ulysses seem to the young women, as he drew near to them all naked as -he was, for he was in great want. On seeing one so unkempt and so -begrimed with salt water, the others scampered off along the spits that -jutted out into the sea, but the daughter of Alcinous stood firm, for -Minerva put courage into her heart and took away all fear from her. She -stood right in front of Ulysses, and he doubted whether he should go up -to her, throw himself at her feet, and embrace her knees as a -suppliant, or stay where he was and entreat her to give him some -clothes and show him the way to the town. In the end he deemed it best -to entreat her from a distance in case the girl should take offence at -his coming near enough to clasp her knees, so he addressed her in -honeyed and persuasive language. - -“O queen,” he said, “I implore your aid—but tell me, are you a goddess -or are you a mortal woman? If you are a goddess and dwell in heaven, I -can only conjecture that you are Jove’s daughter Diana, for your face -and figure resemble none but hers; if on the other hand you are a -mortal and live on earth, thrice happy are your father and -mother—thrice happy, too, are your brothers and sisters; how proud and -delighted they must feel when they see so fair a scion as yourself -going out to a dance; most happy, however, of all will he be whose -wedding gifts have been the richest, and who takes you to his own home. -I never yet saw any one so beautiful, neither man nor woman, and am -lost in admiration as I behold you. I can only compare you to a young -palm tree which I saw when I was at Delos growing near the altar of -Apollo—for I was there, too, with much people after me, when I was on -that journey which has been the source of all my troubles. Never yet -did such a young plant shoot out of the ground as that was, and I -admired and wondered at it exactly as I now admire and wonder at -yourself. I dare not clasp your knees, but I am in great distress; -yesterday made the twentieth day that I had been tossing about upon the -sea. The winds and waves have taken me all the way from the Ogygian -island,55 and now fate has flung me upon this coast that I may endure -still further suffering; for I do not think that I have yet come to the -end of it, but rather that heaven has still much evil in store for me. - -“And now, O queen, have pity upon me, for you are the first person I -have met, and I know no one else in this country. Show me the way to -your town, and let me have anything that you may have brought hither to -wrap your clothes in. May heaven grant you in all things your heart’s -desire—husband, house, and a happy, peaceful home; for there is nothing -better in this world than that man and wife should be of one mind in a -house. It discomfits their enemies, makes the hearts of their friends -glad, and they themselves know more about it than any one.” - -To this Nausicaa answered, “Stranger, you appear to be a sensible, -well-disposed person. There is no accounting for luck; Jove gives -prosperity to rich and poor just as he chooses, so you must take what -he has seen fit to send you, and make the best of it. Now, however, -that you have come to this our country, you shall not want for clothes -nor for anything else that a foreigner in distress may reasonably look -for. I will show you the way to the town, and will tell you the name of -our people; we are called Phaeacians, and I am daughter to Alcinous, in -whom the whole power of the state is vested.” - -Then she called her maids and said, “Stay where you are, you girls. Can -you not see a man without running away from him? Do you take him for a -robber or a murderer? Neither he nor any one else can come here to do -us Phaeacians any harm, for we are dear to the gods, and live apart on -a land’s end that juts into the sounding sea, and have nothing to do -with any other people. This is only some poor man who has lost his way, -and we must be kind to him, for strangers and foreigners in distress -are under Jove’s protection, and will take what they can get and be -thankful; so, girls, give the poor fellow something to eat and drink, -and wash him in the stream at some place that is sheltered from the -wind.” - -On this the maids left off running away and began calling one another -back. They made Ulysses sit down in the shelter as Nausicaa had told -them, and brought him a shirt and cloak. They also brought him the -little golden cruse of oil, and told him to go and wash in the stream. -But Ulysses said, “Young women, please to stand a little on one side -that I may wash the brine from my shoulders and anoint myself with oil, -for it is long enough since my skin has had a drop of oil upon it. I -cannot wash as long as you all keep standing there. I am ashamed to -strip56 before a number of good looking young women.” - -Then they stood on one side and went to tell the girl, while Ulysses -washed himself in the stream and scrubbed the brine from his back and -from his broad shoulders. When he had thoroughly washed himself, and -had got the brine out of his hair, he anointed himself with oil, and -put on the clothes which the girl had given him; Minerva then made him -look taller and stronger than before, she also made the hair grow thick -on the top of his head, and flow down in curls like hyacinth blossoms; -she glorified him about the head and shoulders as a skilful workman who -has studied art of all kinds under Vulcan and Minerva enriches a piece -of silver plate by gilding it—and his work is full of beauty. Then he -went and sat down a little way off upon the beach, looking quite young -and handsome, and the girl gazed on him with admiration; then she said -to her maids: - -“Hush, my dears, for I want to say something. I believe the gods who -live in heaven have sent this man to the Phaeacians. When I first saw -him I thought him plain, but now his appearance is like that of the -gods who dwell in heaven. I should like my future husband to be just -such another as he is, if he would only stay here and not want to go -away. However, give him something to eat and drink.” - -They did as they were told, and set food before Ulysses, who ate and -drank ravenously, for it was long since he had had food of any kind. -Meanwhile, Nausicaa bethought her of another matter. She got the linen -folded and placed in the waggon, she then yoked the mules, and, as she -took her seat, she called Ulysses: - -“Stranger,” said she, “rise and let us be going back to the town; I -will introduce you at the house of my excellent father, where I can -tell you that you will meet all the best people among the Phaeacians. -But be sure and do as I bid you, for you seem to be a sensible person. -As long as we are going past the fields and farm lands, follow briskly -behind the waggon along with the maids and I will lead the way myself. -Presently, however, we shall come to the town, where you will find a -high wall running all round it, and a good harbour on either side with -a narrow entrance into the city, and the ships will be drawn up by the -road side, for every one has a place where his own ship can lie. You -will see the market place with a temple of Neptune in the middle of it, -and paved with large stones bedded in the earth. Here people deal in -ship’s gear of all kinds, such as cables and sails, and here, too, are -the places where oars are made, for the Phaeacians are not a nation of -archers; they know nothing about bows and arrows, but are a sea-faring -folk, and pride themselves on their masts, oars, and ships, with which -they travel far over the sea. - -“I am afraid of the gossip and scandal that may be set on foot against -me later on; for the people here are very ill-natured, and some low -fellow, if he met us, might say, ‘Who is this fine-looking stranger -that is going about with Nausicaa? Where did she find him? I suppose -she is going to marry him. Perhaps he is a vagabond sailor whom she has -taken from some foreign vessel, for we have no neighbours; or some god -has at last come down from heaven in answer to her prayers, and she is -going to live with him all the rest of her life. It would be a good -thing if she would take herself off and find a husband somewhere else, -for she will not look at one of the many excellent young Phaeacians who -are in love with her.’ This is the kind of disparaging remark that -would be made about me, and I could not complain, for I should myself -be scandalised at seeing any other girl do the like, and go about with -men in spite of everybody, while her father and mother were still -alive, and without having been married in the face of all the world. - -“If, therefore, you want my father to give you an escort and to help -you home, do as I bid you; you will see a beautiful grove of poplars by -the road side dedicated to Minerva; it has a well in it and a meadow -all round it. Here my father has a field of rich garden ground, about -as far from the town as a man’s voice will carry. Sit down there and -wait for a while till the rest of us can get into the town and reach my -father’s house. Then, when you think we must have done this, come into -the town and ask the way to the house of my father Alcinous. You will -have no difficulty in finding it; any child will point it out to you, -for no one else in the whole town has anything like such a fine house -as he has. When you have got past the gates and through the outer -court, go right across the inner court till you come to my mother. You -will find her sitting by the fire and spinning her purple wool by -firelight. It is a fine sight to see her as she leans back against one -of the bearing-posts with her maids all ranged behind her. Close to her -seat stands that of my father, on which he sits and topes like an -immortal god. Never mind him, but go up to my mother, and lay your -hands upon her knees if you would get home quickly. If you can gain her -over, you may hope to see your own country again, no matter how distant -it may be.” - -So saying she lashed the mules with her whip and they left the river. -The mules drew well, and their hoofs went up and down upon the road. -She was careful not to go too fast for Ulysses and the maids who were -following on foot along with the waggon, so she plied her whip with -judgement. As the sun was going down they came to the sacred grove of -Minerva, and there Ulysses sat down and prayed to the mighty daughter -of Jove. - -“Hear me,” he cried, “daughter of Aegis-bearing Jove, unweariable, hear -me now, for you gave no heed to my prayers when Neptune was wrecking -me. Now, therefore, have pity upon me and grant that I may find friends -and be hospitably received by the Phaeacians.” - -Thus did he pray, and Minerva heard his prayer, but she would not show -herself to him openly, for she was afraid of her uncle Neptune, who was -still furious in his endeavors to prevent Ulysses from getting home. - - - - -BOOK VII - - -RECEPTION OF ULYSSES AT THE PALACE OF KING ALCINOUS. - - -Thus, then, did Ulysses wait and pray; but the girl drove on to the -town. When she reached her father’s house she drew up at the gateway, -and her brothers—comely as the gods—gathered round her, took the mules -out of the waggon, and carried the clothes into the house, while she -went to her own room, where an old servant, Eurymedusa of Apeira, lit -the fire for her. This old woman had been brought by sea from Apeira, -and had been chosen as a prize for Alcinous because he was king over -the Phaeacians, and the people obeyed him as though he were a god.57 -She had been nurse to Nausicaa, and had now lit the fire for her, and -brought her supper for her into her own room. - -Presently Ulysses got up to go towards the town; and Minerva shed a -thick mist all round him to hide him in case any of the proud -Phaeacians who met him should be rude to him, or ask him who he was. -Then, as he was just entering the town, she came towards him in the -likeness of a little girl carrying a pitcher. She stood right in front -of him, and Ulysses said: - -“My dear, will you be so kind as to show me the house of king Alcinous? -I am an unfortunate foreigner in distress, and do not know one in your -town and country.” - -Then Minerva said, “Yes, father stranger, I will show you the house you -want, for Alcinous lives quite close to my own father. I will go before -you and show the way, but say not a word as you go, and do not look at -any man, nor ask him questions; for the people here cannot abide -strangers, and do not like men who come from some other place. They are -a sea-faring folk, and sail the seas by the grace of Neptune in ships -that glide along like thought, or as a bird in the air.” - -On this she led the way, and Ulysses followed in her steps; but not one -of the Phaeacians could see him as he passed through the city in the -midst of them; for the great goddess Minerva in her good will towards -him had hidden him in a thick cloud of darkness. He admired their -harbours, ships, places of assembly, and the lofty walls of the city, -which, with the palisade on top of them, were very striking, and when -they reached the king’s house Minerva said: - -“This is the house, father stranger, which you would have me show you. -You will find a number of great people sitting at table, but do not be -afraid; go straight in, for the bolder a man is the more likely he is -to carry his point, even though he is a stranger. First find the queen. -Her name is Arete, and she comes of the same family as her husband -Alcinous. They both descend originally from Neptune, who was father to -Nausithous by Periboea, a woman of great beauty. Periboea was the -youngest daughter of Eurymedon, who at one time reigned over the -giants, but he ruined his ill-fated people and lost his own life to -boot. - -“Neptune, however, lay with his daughter, and she had a son by him, the -great Nausithous, who reigned over the Phaeacians. Nausithous had two -sons Rhexenor and Alcinous;58 Apollo killed the first of them while he -was still a bridegroom and without male issue; but he left a daughter -Arete, whom Alcinous married, and honours as no other woman is honoured -of all those that keep house along with their husbands. - -“Thus she both was, and still is, respected beyond measure by her -children, by Alcinous himself, and by the whole people, who look upon -her as a goddess, and greet her whenever she goes about the city, for -she is a thoroughly good woman both in head and heart, and when any -women are friends of hers, she will help their husbands also to settle -their disputes. If you can gain her good will, you may have every hope -of seeing your friends again, and getting safely back to your home and -country.” - -Then Minerva left Scheria and went away over the sea. She went to -Marathon59 and to the spacious streets of Athens, where she entered the -abode of Erechtheus; but Ulysses went on to the house of Alcinous, and -he pondered much as he paused a while before reaching the threshold of -bronze, for the splendour of the palace was like that of the sun or -moon. The walls on either side were of bronze from end to end, and the -cornice was of blue enamel. The doors were gold, and hung on pillars of -silver that rose from a floor of bronze, while the lintel was silver -and the hook of the door was of gold. - -On either side there stood gold and silver mastiffs which Vulcan, with -his consummate skill, had fashioned expressly to keep watch over the -palace of king Alcinous; so they were immortal and could never grow -old. Seats were ranged all along the wall, here and there from one end -to the other, with coverings of fine woven work which the women of the -house had made. Here the chief persons of the Phaeacians used to sit -and eat and drink, for there was abundance at all seasons; and there -were golden figures of young men with lighted torches in their hands, -raised on pedestals, to give light by night to those who were at table. -There are60 fifty maid servants in the house, some of whom are always -grinding rich yellow grain at the mill, while others work at the loom, -or sit and spin, and their shuttles go backwards and forwards like the -fluttering of aspen leaves, while the linen is so closely woven that it -will turn oil. As the Phaeacians are the best sailors in the world, so -their women excel all others in weaving, for Minerva has taught them -all manner of useful arts, and they are very intelligent. - -Outside the gate of the outer court there is a large garden of about -four acres with a wall all round it. It is full of beautiful -trees—pears, pomegranates, and the most delicious apples. There are -luscious figs also, and olives in full growth. The fruits never rot nor -fail all the year round, neither winter nor summer, for the air is so -soft that a new crop ripens before the old has dropped. Pear grows on -pear, apple on apple, and fig on fig, and so also with the grapes, for -there is an excellent vineyard: on the level ground of a part of this, -the grapes are being made into raisins; in another part they are being -gathered; some are being trodden in the wine tubs, others further on -have shed their blossom and are beginning to show fruit, others again -are just changing colour. In the furthest part of the ground there are -beautifully arranged beds of flowers that are in bloom all the year -round. Two streams go through it, the one turned in ducts throughout -the whole garden, while the other is carried under the ground of the -outer court to the house itself, and the town’s people draw water from -it. Such, then, were the splendours with which the gods had endowed the -house of king Alcinous. - -So here Ulysses stood for a while and looked about him, but when he had -looked long enough he crossed the threshold and went within the -precincts of the house. There he found all the chief people among the -Phaeacians making their drink offerings to Mercury, which they always -did the last thing before going away for the night.61 He went straight -through the court, still hidden by the cloak of darkness in which -Minerva had enveloped him, till he reached Arete and King Alcinous; -then he laid his hands upon the knees of the queen, and at that moment -the miraculous darkness fell away from him and he became visible. Every -one was speechless with surprise at seeing a man there, but Ulysses -began at once with his petition. - -“Queen Arete,” he exclaimed, “daughter of great Rhexenor, in my -distress I humbly pray you, as also your husband and these your guests -(whom may heaven prosper with long life and happiness, and may they -leave their possessions to their children, and all the honours -conferred upon them by the state) to help me home to my own country as -soon as possible; for I have been long in trouble and away from my -friends.” - -Then he sat down on the hearth among the ashes and they all held their -peace, till presently the old hero Echeneus, who was an excellent -speaker and an elder among the Phaeacians, plainly and in all honesty -addressed them thus: - -“Alcinous,” said he, “it is not creditable to you that a stranger -should be seen sitting among the ashes of your hearth; every one is -waiting to hear what you are about to say; tell him, then, to rise and -take a seat on a stool inlaid with silver, and bid your servants mix -some wine and water that we may make a drink offering to Jove the lord -of thunder, who takes all well disposed suppliants under his -protection; and let the housekeeper give him some supper, of whatever -there may be in the house.” - -When Alcinous heard this he took Ulysses by the hand, raised him from -the hearth, and bade him take the seat of Laodamas, who had been -sitting beside him, and was his favourite son. A maid servant then -brought him water in a beautiful golden ewer and poured it into a -silver basin for him to wash his hands, and she drew a clean table -beside him; an upper servant brought him bread and offered him many -good things of what there was in the house, and Ulysses ate and drank. -Then Alcinous said to one of the servants, “Pontonous, mix a cup of -wine and hand it round that we may make drink-offerings to Jove the -lord of thunder, who is the protector of all well-disposed suppliants.” - -Pontonous then mixed wine and water, and handed it round after giving -every man his drink-offering. When they had made their offerings, and -had drunk each as much as he was minded, Alcinous said: - -“Aldermen and town councillors of the Phaeacians, hear my words. You -have had your supper, so now go home to bed. To-morrow morning I shall -invite a still larger number of aldermen, and will give a sacrificial -banquet in honour of our guest; we can then discuss the question of his -escort, and consider how we may at once send him back rejoicing to his -own country without trouble or inconvenience to himself, no matter how -distant it may be. We must see that he comes to no harm while on his -homeward journey, but when he is once at home he will have to take the -luck he was born with for better or worse like other people. It is -possible, however, that the stranger is one of the immortals who has -come down from heaven to visit us; but in this case the gods are -departing from their usual practice, for hitherto they have made -themselves perfectly clear to us when we have been offering them -hecatombs. They come and sit at our feasts just like one of our selves, -and if any solitary wayfarer happens to stumble upon some one or other -of them, they affect no concealment, for we are as near of kin to the -gods as the Cyclopes and the savage giants are.”62 - -Then Ulysses said: “Pray, Alcinous, do not take any such notion into -your head. I have nothing of the immortal about me, neither in body nor -mind, and most resemble those among you who are the most afflicted. -Indeed, were I to tell you all that heaven has seen fit to lay upon me, -you would say that I was still worse off than they are. Nevertheless, -let me sup in spite of sorrow, for an empty stomach is a very -importunate thing, and thrusts itself on a man’s notice no matter how -dire is his distress. I am in great trouble, yet it insists that I -shall eat and drink, bids me lay aside all memory of my sorrows and -dwell only on the due replenishing of itself. As for yourselves, do as -you propose, and at break of day set about helping me to get home. I -shall be content to die if I may first once more behold my property, my -bondsmen, and all the greatness of my house.”63 - -Thus did he speak. Every one approved his saying, and agreed that he -should have his escort inasmuch as he had spoken reasonably. Then when -they had made their drink offerings, and had drunk each as much as he -was minded they went home to bed every man in his own abode, leaving -Ulysses in the cloister with Arete and Alcinous while the servants were -taking the things away after supper. Arete was the first to speak, for -she recognised the shirt, cloak, and good clothes that Ulysses was -wearing, as the work of herself and of her maids; so she said, -“Stranger, before we go any further, there is a question I should like -to ask you. Who, and whence are you, and who gave you those clothes? -Did you not say you had come here from beyond the sea?” - -And Ulysses answered, “It would be a long story Madam, were I to relate -in full the tale of my misfortunes, for the hand of heaven has been -laid heavy upon me; but as regards your question, there is an island -far away in the sea which is called ‘the Ogygian.’ Here dwells the -cunning and powerful goddess Calypso, daughter of Atlas. She lives by -herself far from all neighbours human or divine. Fortune, however, -brought me to her hearth all desolate and alone, for Jove struck my -ship with his thunderbolts, and broke it up in mid-ocean. My brave -comrades were drowned every man of them, but I stuck to the keel and -was carried hither and thither for the space of nine days, till at last -during the darkness of the tenth night the gods brought me to the -Ogygian island where the great goddess Calypso lives. She took me in -and treated me with the utmost kindness; indeed she wanted to make me -immortal that I might never grow old, but she could not persuade me to -let her do so. - -“I stayed with Calypso seven years straight on end, and watered the -good clothes she gave me with my tears during the whole time; but at -last when the eighth year came round she bade me depart of her own free -will, either because Jove had told her she must, or because she had -changed her mind. She sent me from her island on a raft, which she -provisioned with abundance of bread and wine. Moreover she gave me good -stout clothing, and sent me a wind that blew both warm and fair. Days -seven and ten did I sail over the sea, and on the eighteenth I caught -sight of the first outlines of the mountains upon your coast—and glad -indeed was I to set eyes upon them. Nevertheless there was still much -trouble in store for me, for at this point Neptune would let me go no -further, and raised a great storm against me; the sea was so terribly -high that I could no longer keep to my raft, which went to pieces under -the fury of the gale, and I had to swim for it, till wind and current -brought me to your shores. - -“There I tried to land, but could not, for it was a bad place and the -waves dashed me against the rocks, so I again took to the sea and swam -on till I came to a river that seemed the most likely landing place, -for there were no rocks and it was sheltered from the wind. Here, then, -I got out of the water and gathered my senses together again. Night was -coming on, so I left the river, and went into a thicket, where I -covered myself all over with leaves, and presently heaven sent me off -into a very deep sleep. Sick and sorry as I was I slept among the -leaves all night, and through the next day till afternoon, when I woke -as the sun was westering, and saw your daughter’s maid servants playing -upon the beach, and your daughter among them looking like a goddess. I -besought her aid, and she proved to be of an excellent disposition, -much more so than could be expected from so young a person—for young -people are apt to be thoughtless. She gave me plenty of bread and wine, -and when she had had me washed in the river she also gave me the -clothes in which you see me. Now, therefore, though it has pained me to -do so, I have told you the whole truth.” - -Then Alcinous said, “Stranger, it was very wrong of my daughter not to -bring you on at once to my house along with the maids, seeing that she -was the first person whose aid you asked.” - -“Pray do not scold her,” replied Ulysses; “she is not to blame. She did -tell me to follow along with the maids, but I was ashamed and afraid, -for I thought you might perhaps be displeased if you saw me. Every -human being is sometimes a little suspicious and irritable.” - -“Stranger,” replied Alcinous, “I am not the kind of man to get angry -about nothing; it is always better to be reasonable; but by Father -Jove, Minerva, and Apollo, now that I see what kind of person you are, -and how much you think as I do, I wish you would stay here, marry my -daughter, and become my son-in-law. If you will stay I will give you a -house and an estate, but no one (heaven forbid) shall keep you here -against your own wish, and that you may be sure of this I will attend -tomorrow to the matter of your escort. You can sleep64 during the whole -voyage if you like, and the men shall sail you over smooth waters -either to your own home, or wherever you please, even though it be a -long way further off than Euboea, which those of my people who saw it -when they took yellow-haired Rhadamanthus to see Tityus the son of -Gaia, tell me is the furthest of any place—and yet they did the whole -voyage in a single day without distressing themselves, and came back -again afterwards. You will thus see how much my ships excel all others, -and what magnificent oarsmen my sailors are.” - -Then was Ulysses glad and prayed aloud saying, “Father Jove, grant that -Alcinous may do all as he has said, for so he will win an imperishable -name among mankind, and at the same time I shall return to my country.” - -Thus did they converse. Then Arete told her maids to set a bed in the -room that was in the gatehouse, and make it with good red rugs, and to -spread coverlets on the top of them with woollen cloaks for Ulysses to -wear. The maids thereon went out with torches in their hands, and when -they had made the bed they came up to Ulysses and said, “Rise, sir -stranger, and come with us for your bed is ready,” and glad indeed was -he to go to his rest. - -So Ulysses slept in a bed placed in a room over the echoing gateway; -but Alcinous lay in the inner part of the house, with the queen his -wife by his side. - - - - -BOOK VIII - - -BANQUET IN THE HOUSE OF ALCINOUS—THE GAMES. - - -Now when the child of morning, rosy-fingered Dawn, appeared, Alcinous -and Ulysses both rose, and Alcinous led the way to the Phaeacian place -of assembly, which was near the ships. When they got there they sat -down side by side on a seat of polished stone, while Minerva took the -form of one of Alcinous’ servants, and went round the town in order to -help Ulysses to get home. She went up to the citizens, man by man, and -said, “Aldermen and town councillors of the Phaeacians, come to the -assembly all of you and listen to the stranger who has just come off a -long voyage to the house of King Alcinous; he looks like an immortal -god.” - -With these words she made them all want to come, and they flocked to -the assembly till seats and standing room were alike crowded. Every one -was struck with the appearance of Ulysses, for Minerva had beautified -him about the head and shoulders, making him look taller and stouter -than he really was, that he might impress the Phaeacians favourably as -being a very remarkable man, and might come off well in the many trials -of skill to which they would challenge him. Then, when they were got -together, Alcinous spoke: - -“Hear me,” said he, “aldermen and town councillors of the Phaeacians, -that I may speak even as I am minded. This stranger, whoever he may be, -has found his way to my house from somewhere or other either East or -West. He wants an escort and wishes to have the matter settled. Let us -then get one ready for him, as we have done for others before him; -indeed, no one who ever yet came to my house has been able to complain -of me for not speeding on his way soon enough. Let us draw a ship into -the sea—one that has never yet made a voyage—and man her with two and -fifty of our smartest young sailors. Then when you have made fast your -oars each by his own seat, leave the ship and come to my house to -prepare a feast.65 I will find you in everything. I am giving these -instructions to the young men who will form the crew, for as regards -you aldermen and town councillors, you will join me in entertaining our -guest in the cloisters. I can take no excuses, and we will have -Demodocus to sing to us; for there is no bard like him whatever he may -choose to sing about.” - -Alcinous then led the way, and the others followed after, while a -servant went to fetch Demodocus. The fifty-two picked oarsmen went to -the sea shore as they had been told, and when they got there they drew -the ship into the water, got her mast and sails inside her, bound the -oars to the thole-pins with twisted thongs of leather, all in due -course, and spread the white sails aloft. They moored the vessel a -little way out from land, and then came on shore and went to the house -of King Alcinous. The out houses,66 yards, and all the precincts were -filled with crowds of men in great multitudes both old and young; and -Alcinous killed them a dozen sheep, eight full grown pigs, and two -oxen. These they skinned and dressed so as to provide a magnificent -banquet. - -A servant presently led in the famous bard Demodocus, whom the muse had -dearly loved, but to whom she had given both good and evil, for though -she had endowed him with a divine gift of song, she had robbed him of -his eyesight. Pontonous set a seat for him among the guests, leaning it -up against a bearing-post. He hung the lyre for him on a peg over his -head, and showed him where he was to feel for it with his hands. He -also set a fair table with a basket of victuals by his side, and a cup -of wine from which he might drink whenever he was so disposed. - -The company then laid their hands upon the good things that were before -them, but as soon as they had had enough to eat and drink, the muse -inspired Demodocus to sing the feats of heroes, and more especially a -matter that was then in the mouths of all men, to wit, the quarrel -between Ulysses and Achilles, and the fierce words that they heaped on -one another as they sat together at a banquet. But Agamemnon was glad -when he heard his chieftains quarrelling with one another, for Apollo -had foretold him this at Pytho when he crossed the stone floor to -consult the oracle. Here was the beginning of the evil that by the will -of Jove fell both upon Danaans and Trojans. - -Thus sang the bard, but Ulysses drew his purple mantle over his head -and covered his face, for he was ashamed to let the Phaeacians see that -he was weeping. When the bard left off singing he wiped the tears from -his eyes, uncovered his face, and, taking his cup, made a -drink-offering to the gods; but when the Phaeacians pressed Demodocus -to sing further, for they delighted in his lays, then Ulysses again -drew his mantle over his head and wept bitterly. No one noticed his -distress except Alcinous, who was sitting near him, and heard the heavy -sighs that he was heaving. So he at once said, “Aldermen and town -councillors of the Phaeacians, we have had enough now, both of the -feast, and of the minstrelsy that is its due accompaniment; let us -proceed therefore to the athletic sports, so that our guest on his -return home may be able to tell his friends how much we surpass all -other nations as boxers, wrestlers, jumpers, and runners.” - -With these words he led the way, and the others followed after. A -servant hung Demodocus’s lyre on its peg for him, led him out of the -cloister, and set him on the same way as that along which all the chief -men of the Phaeacians were going to see the sports; a crowd of several -thousands of people followed them, and there were many excellent -competitors for all the prizes. Acroneos, Ocyalus, Elatreus, Nauteus, -Prymneus, Anchialus, Eretmeus, Ponteus, Proreus, Thoon, Anabesineus, -and Amphialus son of Polyneus son of Tecton. There was also Euryalus -son of Naubolus, who was like Mars himself, and was the best looking -man among the Phaeacians except Laodamas. Three sons of Alcinous, -Laodamas, Halios, and Clytoneus, competed also. - -The foot races came first. The course was set out for them from the -starting post, and they raised a dust upon the plain as they all flew -forward at the same moment. Clytoneus came in first by a long way; he -left every one else behind him by the length of the furrow that a -couple of mules can plough in a fallow field.67 They then turned to the -painful art of wrestling, and here Euryalus proved to be the best man. -Amphialus excelled all the others in jumping, while at throwing the -disc there was no one who could approach Elatreus. Alcinous’s son -Laodamas was the best boxer, and he it was who presently said, when -they had all been diverted with the games, “Let us ask the stranger -whether he excels in any of these sports; he seems very powerfully -built; his thighs, calves, hands, and neck are of prodigious strength, -nor is he at all old, but he has suffered much lately, and there is -nothing like the sea for making havoc with a man, no matter how strong -he is.” - -“You are quite right, Laodamas,” replied Euryalus, “go up to your guest -and speak to him about it yourself.” - -When Laodamas heard this he made his way into the middle of the crowd -and said to Ulysses, “I hope, Sir, that you will enter yourself for -some one or other of our competitions if you are skilled in any of -them—and you must have gone in for many a one before now. There is -nothing that does any one so much credit all his life long as the -showing himself a proper man with his hands and feet. Have a try -therefore at something, and banish all sorrow from your mind. Your -return home will not be long delayed, for the ship is already drawn -into the water, and the crew is found.” - -Ulysses answered, “Laodamas, why do you taunt me in this way? my mind -is set rather on cares than contests; I have been through infinite -trouble, and am come among you now as a suppliant, praying your king -and people to further me on my return home.” - -Then Euryalus reviled him outright and said, “I gather, then, that you -are unskilled in any of the many sports that men generally delight in. -I suppose you are one of those grasping traders that go about in ships -as captains or merchants, and who think of nothing but of their outward -freights and homeward cargoes. There does not seem to be much of the -athlete about you.” - -“For shame, Sir,” answered Ulysses, fiercely, “you are an insolent -fellow—so true is it that the gods do not grace all men alike in -speech, person, and understanding. One man may be of weak presence, but -heaven has adorned this with such a good conversation that he charms -every one who sees him; his honeyed moderation carries his hearers with -him so that he is leader in all assemblies of his fellows, and wherever -he goes he is looked up to. Another may be as handsome as a god, but -his good looks are not crowned with discretion. This is your case. No -god could make a finer looking fellow than you are, but you are a fool. -Your ill-judged remarks have made me exceedingly angry, and you are -quite mistaken, for I excel in a great many athletic exercises; indeed, -so long as I had youth and strength, I was among the first athletes of -the age. Now, however, I am worn out by labour and sorrow, for I have -gone through much both on the field of battle and by the waves of the -weary sea; still, in spite of all this I will compete, for your taunts -have stung me to the quick.” - -So he hurried up without even taking his cloak off, and seized a disc, -larger, more massive and much heavier than those used by the Phaeacians -when disc-throwing among themselves.68 Then, swinging it back, he threw -it from his brawny hand, and it made a humming sound in the air as he -did so. The Phaeacians quailed beneath the rushing of its flight as it -sped gracefully from his hand, and flew beyond any mark that had been -made yet. Minerva, in the form of a man, came and marked the place -where it had fallen. “A blind man, Sir,” said she, “could easily tell -your mark by groping for it—it is so far ahead of any other. You may -make your mind easy about this contest, for no Phaeacian can come near -to such a throw as yours.” - -Ulysses was glad when he found he had a friend among the lookers-on, so -he began to speak more pleasantly. “Young men,” said he, “come up to -that throw if you can, and I will throw another disc as heavy or even -heavier. If anyone wants to have a bout with me let him come on, for I -am exceedingly angry; I will box, wrestle, or run, I do not care what -it is, with any man of you all except Laodamas, but not with him -because I am his guest, and one cannot compete with one’s own personal -friend. At least I do not think it a prudent or a sensible thing for a -guest to challenge his host’s family at any game, especially when he is -in a foreign country. He will cut the ground from under his own feet if -he does; but I make no exception as regards any one else, for I want to -have the matter out and know which is the best man. I am a good hand at -every kind of athletic sport known among mankind. I am an excellent -archer. In battle I am always the first to bring a man down with my -arrow, no matter how many more are taking aim at him alongside of me. -Philoctetes was the only man who could shoot better than I could when -we Achaeans were before Troy and in practice. I far excel every one -else in the whole world, of those who still eat bread upon the face of -the earth, but I should not like to shoot against the mighty dead, such -as Hercules, or Eurytus the Oechalian—men who could shoot against the -gods themselves. This in fact was how Eurytus came prematurely by his -end, for Apollo was angry with him and killed him because he challenged -him as an archer. I can throw a dart farther than any one else can -shoot an arrow. Running is the only point in respect of which I am -afraid some of the Phaeacians might beat me, for I have been brought -down very low at sea; my provisions ran short, and therefore I am still -weak.” - -They all held their peace except King Alcinous, who began, “Sir, we -have had much pleasure in hearing all that you have told us, from which -I understand that you are willing to show your prowess, as having been -displeased with some insolent remarks that have been made to you by one -of our athletes, and which could never have been uttered by any one who -knows how to talk with propriety. I hope you will apprehend my meaning, -and will explain to any one of your chief men who may be dining with -yourself and your family when you get home, that we have an hereditary -aptitude for accomplishments of all kinds. We are not particularly -remarkable for our boxing, nor yet as wrestlers, but we are singularly -fleet of foot and are excellent sailors. We are extremely fond of good -dinners, music, and dancing; we also like frequent changes of linen, -warm baths, and good beds, so now, please, some of you who are the best -dancers set about dancing, that our guest on his return home may be -able to tell his friends how much we surpass all other nations as -sailors, runners, dancers, and minstrels. Demodocus has left his lyre -at my house, so run some one or other of you and fetch it for him.” - -On this a servant hurried off to bring the lyre from the king’s house, -and the nine men who had been chosen as stewards stood forward. It was -their business to manage everything connected with the sports, so they -made the ground smooth and marked a wide space for the dancers. -Presently the servant came back with Demodocus’s lyre, and he took his -place in the midst of them, whereon the best young dancers in the town -began to foot and trip it so nimbly that Ulysses was delighted with the -merry twinkling of their feet. - -Meanwhile the bard began to sing the loves of Mars and Venus, and how -they first began their intrigue in the house of Vulcan. Mars made Venus -many presents, and defiled King Vulcan’s marriage bed, so the sun, who -saw what they were about, told Vulcan. Vulcan was very angry when he -heard such dreadful news, so he went to his smithy brooding mischief, -got his great anvil into its place, and began to forge some chains -which none could either unloose or break, so that they might stay there -in that place.69 When he had finished his snare he went into his -bedroom and festooned the bed-posts all over with chains like cobwebs; -he also let many hang down from the great beam of the ceiling. Not even -a god could see them so fine and subtle were they. As soon as he had -spread the chains all over the bed, he made as though he were setting -out for the fair state of Lemnos, which of all places in the world was -the one he was most fond of. But Mars kept no blind look out, and as -soon as he saw him start, hurried off to his house, burning with love -for Venus. - -Now Venus was just come in from a visit to her father Jove, and was -about sitting down when Mars came inside the house, and said as he took -her hand in his own, “Let us go to the couch of Vulcan: he is not at -home, but is gone off to Lemnos among the Sintians, whose speech is -barbarous.” - -She was nothing loth, so they went to the couch to take their rest, -whereon they were caught in the toils which cunning Vulcan had spread -for them, and could neither get up nor stir hand or foot, but found too -late that they were in a trap. Then Vulcan came up to them, for he had -turned back before reaching Lemnos, when his scout the sun told him -what was going on. He was in a furious passion, and stood in the -vestibule making a dreadful noise as he shouted to all the gods. - -“Father Jove,” he cried, “and all you other blessed gods who live for -ever, come here and see the ridiculous and disgraceful sight that I -will show you. Jove’s daughter Venus is always dishonouring me because -I am lame. She is in love with Mars, who is handsome and clean built, -whereas I am a cripple—but my parents are to blame for that, not I; -they ought never to have begotten me. Come and see the pair together -asleep on my bed. It makes me furious to look at them. They are very -fond of one another, but I do not think they will lie there longer than -they can help, nor do I think that they will sleep much; there, -however, they shall stay till her father has repaid me the sum I gave -him for his baggage of a daughter, who is fair but not honest.” - -On this the gods gathered to the house of Vulcan. Earth-encircling -Neptune came, and Mercury the bringer of luck, and King Apollo, but the -goddesses staid at home all of them for shame. Then the givers of all -good things stood in the doorway, and the blessed gods roared with -inextinguishable laughter, as they saw how cunning Vulcan had been, -whereon one would turn towards his neighbour saying: - -“Ill deeds do not prosper, and the weak confound the strong. See how -limping Vulcan, lame as he is, has caught Mars who is the fleetest god -in heaven; and now Mars will be cast in heavy damages.” - -Thus did they converse, but King Apollo said to Mercury, “Messenger -Mercury, giver of good things, you would not care how strong the chains -were, would you, if you could sleep with Venus?” - -“King Apollo,” answered Mercury, “I only wish I might get the chance, -though there were three times as many chains—and you might look on, all -of you, gods and goddesses, but I would sleep with her if I could.” - -The immortal gods burst out laughing as they heard him, but Neptune -took it all seriously, and kept on imploring Vulcan to set Mars free -again. “Let him go,” he cried, “and I will undertake, as you require, -that he shall pay you all the damages that are held reasonable among -the immortal gods.” - -“Do not,” replied Vulcan, “ask me to do this; a bad man’s bond is bad -security; what remedy could I enforce against you if Mars should go -away and leave his debts behind him along with his chains?” - -“Vulcan,” said Neptune, “if Mars goes away without paying his damages, -I will pay you myself.” So Vulcan answered, “In this case I cannot and -must not refuse you.” - -Thereon he loosed the bonds that bound them, and as soon as they were -free they scampered off, Mars to Thrace and laughter-loving Venus to -Cyprus and to Paphos, where is her grove and her altar fragrant with -burnt offerings. Here the Graces bathed her, and anointed her with oil -of ambrosia such as the immortal gods make use of, and they clothed her -in raiment of the most enchanting beauty. - -Thus sang the bard, and both Ulysses and the seafaring Phaeacians were -charmed as they heard him. - -Then Alcinous told Laodamas and Halius to dance alone, for there was no -one to compete with them. So they took a red ball which Polybus had -made for them, and one of them bent himself backwards and threw it up -towards the clouds, while the other jumped from off the ground and -caught it with ease before it came down again. When they had done -throwing the ball straight up into the air they began to dance, and at -the same time kept on throwing it backwards and forwards to one -another, while all the young men in the ring applauded and made a great -stamping with their feet. Then Ulysses said: - -“King Alcinous, you said your people were the nimblest dancers in the -world, and indeed they have proved themselves to be so. I was -astonished as I saw them.” - -The king was delighted at this, and exclaimed to the Phaeacians, -“Aldermen and town councillors, our guest seems to be a person of -singular judgement; let us give him such proof of our hospitality as he -may reasonably expect. There are twelve chief men among you, and -counting myself there are thirteen; contribute, each of you, a clean -cloak, a shirt, and a talent of fine gold; let us give him all this in -a lump down at once, so that when he gets his supper he may do so with -a light heart. As for Euryalus he will have to make a formal apology -and a present too, for he has been rude.” - -Thus did he speak. The others all of them applauded his saying, and -sent their servants to fetch the presents. Then Euryalus said, “King -Alcinous, I will give the stranger all the satisfaction you require. He -shall have my sword, which is of bronze, all but the hilt, which is of -silver. I will also give him the scabbard of newly sawn ivory into -which it fits. It will be worth a great deal to him.” - -As he spoke he placed the sword in the hands of Ulysses and said, “Good -luck to you, father stranger; if anything has been said amiss may the -winds blow it away with them, and may heaven grant you a safe return, -for I understand you have been long away from home, and have gone -through much hardship.” - -To which Ulysses answered, “Good luck to you too my friend, and may the -gods grant you every happiness. I hope you will not miss the sword you -have given me along with your apology.” - -With these words he girded the sword about his shoulders and towards -sundown the presents began to make their appearance, as the servants of -the donors kept bringing them to the house of King Alcinous; here his -sons received them, and placed them under their mother’s charge. Then -Alcinous led the way to the house and bade his guests take their seats. - -“Wife,” said he, turning to Queen Arete, “Go, fetch the best chest we -have, and put a clean cloak and shirt in it. Also, set a copper on the -fire and heat some water; our guest will take a warm bath; see also to -the careful packing of the presents that the noble Phaeacians have made -him; he will thus better enjoy both his supper and the singing that -will follow. I shall myself give him this golden goblet—which is of -exquisite workmanship—that he may be reminded of me for the rest of his -life whenever he makes a drink offering to Jove, or to any of the -gods.”70 - -Then Arete told her maids to set a large tripod upon the fire as fast -as they could, whereon they set a tripod full of bath water on to a -clear fire; they threw on sticks to make it blaze, and the water became -hot as the flame played about the belly of the tripod.71 Meanwhile -Arete brought a magnificent chest from her own room, and inside it she -packed all the beautiful presents of gold and raiment which the -Phaeacians had brought. Lastly she added a cloak and a good shirt from -Alcinous, and said to Ulysses: - -“See to the lid yourself, and have the whole bound round at once, for -fear any one should rob you by the way when you are asleep in your -ship.” 72 - -When Ulysses heard this he put the lid on the chest and made it fast -with a bond that Circe had taught him. He had done so before an upper -servant told him to come to the bath and wash himself. He was very glad -of a warm bath, for he had had no one to wait upon him ever since he -left the house of Calypso, who as long as he remained with her had -taken as good care of him as though he had been a god. When the -servants had done washing and anointing him with oil, and had given him -a clean cloak and shirt, he left the bath room and joined the guests -who were sitting over their wine. Lovely Nausicaa stood by one of the -bearing-posts supporting the roof of the cloister, and admired him as -she saw him pass. “Farewell stranger,” said she, “do not forget me when -you are safe at home again, for it is to me first that you owe a ransom -for having saved your life.” - -And Ulysses said, “Nausicaa, daughter of great Alcinous, may Jove the -mighty husband of Juno, grant that I may reach my home; so shall I -bless you as my guardian angel all my days, for it was you who saved -me.” - -When he had said this, he seated himself beside Alcinous. Supper was -then served, and the wine was mixed for drinking. A servant led in the -favourite bard Demodocus, and set him in the midst of the company, near -one of the bearing-posts supporting the cloister, that he might lean -against it. Then Ulysses cut off a piece of roast pork with plenty of -fat (for there was abundance left on the joint) and said to a servant, -“Take this piece of pork over to Demodocus and tell him to eat it; for -all the pain his lays may cause me I will salute him none the less; -bards are honoured and respected throughout the world, for the muse -teaches them their songs and loves them.” - -The servant carried the pork in his fingers over to Demodocus, who took -it and was very much pleased. They then laid their hands on the good -things that were before them, and as soon as they had had to eat and -drink, Ulysses said to Demodocus, “Demodocus, there is no one in the -world whom I admire more than I do you. You must have studied under the -Muse, Jove’s daughter, and under Apollo, so accurately do you sing the -return of the Achaeans with all their sufferings and adventures. If you -were not there yourself, you must have heard it all from some one who -was. Now, however, change your song and tell us of the wooden horse -which Epeus made with the assistance of Minerva, and which Ulysses got -by stratagem into the fort of Troy after freighting it with the men who -afterwards sacked the city. If you will sing this tale aright I will -tell all the world how magnificently heaven has endowed you.” - -The bard inspired of heaven took up the story at the point where some -of the Argives set fire to their tents and sailed away while others, -hidden within the horse,73 were waiting with Ulysses in the Trojan -place of assembly. For the Trojans themselves had drawn the horse into -their fortress, and it stood there while they sat in council round it, -and were in three minds as to what they should do. Some were for -breaking it up then and there; others would have it dragged to the top -of the rock on which the fortress stood, and then thrown down the -precipice; while yet others were for letting it remain as an offering -and propitiation for the gods. And this was how they settled it in the -end, for the city was doomed when it took in that horse, within which -were all the bravest of the Argives waiting to bring death and -destruction on the Trojans. Anon he sang how the sons of the Achaeans -issued from the horse, and sacked the town, breaking out from their -ambuscade. He sang how they overran the city hither and thither and -ravaged it, and how Ulysses went raging like Mars along with Menelaus -to the house of Deiphobus. It was there that the fight raged most -furiously, nevertheless by Minerva’s help he was victorious. - -All this he told, but Ulysses was overcome as he heard him, and his -cheeks were wet with tears. He wept as a woman weeps when she throws -herself on the body of her husband who has fallen before his own city -and people, fighting bravely in defence of his home and children. She -screams aloud and flings her arms about him as he lies gasping for -breath and dying, but her enemies beat her from behind about the back -and shoulders, and carry her off into slavery, to a life of labour and -sorrow, and the beauty fades from her cheeks—even so piteously did -Ulysses weep, but none of those present perceived his tears except -Alcinous, who was sitting near him, and could hear the sobs and sighs -that he was heaving. The king, therefore, at once rose and said: - -“Aldermen and town councillors of the Phaeacians, let Demodocus cease -his song, for there are those present who do not seem to like it. From -the moment that we had done supper and Demodocus began to sing, our -guest has been all the time groaning and lamenting. He is evidently in -great trouble, so let the bard leave off, that we may all enjoy -ourselves, hosts and guest alike. This will be much more as it should -be, for all these festivities, with the escort and the presents that we -are making with so much good will are wholly in his honour, and any one -with even a moderate amount of right feeling knows that he ought to -treat a guest and a suppliant as though he were his own brother. - -“Therefore, Sir, do you on your part affect no more concealment nor -reserve in the matter about which I shall ask you; it will be more -polite in you to give me a plain answer; tell me the name by which your -father and mother over yonder used to call you, and by which you were -known among your neighbours and fellow-citizens. There is no one, -neither rich nor poor, who is absolutely without any name whatever, for -people’s fathers and mothers give them names as soon as they are born. -Tell me also your country, nation, and city, that our ships may shape -their purpose accordingly and take you there. For the Phaeacians have -no pilots; their vessels have no rudders as those of other nations -have, but the ships themselves understand what it is that we are -thinking about and want; they know all the cities and countries in the -whole world, and can traverse the sea just as well even when it is -covered with mist and cloud, so that there is no danger of being -wrecked or coming to any harm. Still I do remember hearing my father -say that Neptune was angry with us for being too easy-going in the -matter of giving people escorts. He said that one of these days he -should wreck a ship of ours as it was returning from having escorted -some one,74 and bury our city under a high mountain. This is what my -father used to say, but whether the god will carry out his threat or no -is a matter which he will decide for himself. - -“And now, tell me and tell me true. Where have you been wandering, and -in what countries have you travelled? Tell us of the peoples -themselves, and of their cities—who were hostile, savage and -uncivilised, and who, on the other hand, hospitable and humane. Tell us -also why you are made so unhappy on hearing about the return of the -Argive Danaans from Troy. The gods arranged all this, and sent them -their misfortunes in order that future generations might have something -to sing about. Did you lose some brave kinsman of your wife’s when you -were before Troy? a son-in-law or father-in-law—which are the nearest -relations a man has outside his own flesh and blood? or was it some -brave and kindly-natured comrade—for a good friend is as dear to a man -as his own brother?” - - - - -BOOK IX - - -ULYSSES DECLARES HIMSELF AND BEGINS HIS STORY—-THE CICONS, LOTOPHAGI, -AND CYCLOPES. - - -And Ulysses answered, “King Alcinous, it is a good thing to hear a bard -with such a divine voice as this man has. There is nothing better or -more delightful than when a whole people make merry together, with the -guests sitting orderly to listen, while the table is loaded with bread -and meats, and the cup-bearer draws wine and fills his cup for every -man. This is indeed as fair a sight as a man can see. Now, however, -since you are inclined to ask the story of my sorrows, and rekindle my -own sad memories in respect of them, I do not know how to begin, nor -yet how to continue and conclude my tale, for the hand of heaven has -been laid heavily upon me. - -“Firstly, then, I will tell you my name that you too may know it, and -one day, if I outlive this time of sorrow, may become my guests though -I live so far away from all of you. I am Ulysses son of Laertes, -renowned among mankind for all manner of subtlety, so that my fame -ascends to heaven. I live in Ithaca, where there is a high mountain -called Neritum, covered with forests; and not far from it there is a -group of islands very near to one another—Dulichium, Same, and the -wooded island of Zacynthus. It lies squat on the horizon, all highest -up in the sea towards the sunset, while the others lie away from it -towards dawn.75 It is a rugged island, but it breeds brave men, and my -eyes know none that they better love to look upon. The goddess Calypso -kept me with her in her cave, and wanted me to marry her, as did also -the cunning Aeaean goddess Circe; but they could neither of them -persuade me, for there is nothing dearer to a man than his own country -and his parents, and however splendid a home he may have in a foreign -country, if it be far from father or mother, he does not care about it. -Now, however, I will tell you of the many hazardous adventures which by -Jove’s will I met with on my return from Troy. - -“When I had set sail thence the wind took me first to Ismarus, which is -the city of the Cicons. There I sacked the town and put the people to -the sword. We took their wives and also much booty, which we divided -equitably amongst us, so that none might have reason to complain. I -then said that we had better make off at once, but my men very -foolishly would not obey me, so they staid there drinking much wine and -killing great numbers of sheep and oxen on the sea shore. Meanwhile the -Cicons cried out for help to other Cicons who lived inland. These were -more in number, and stronger, and they were more skilled in the art of -war, for they could fight, either from chariots or on foot as the -occasion served; in the morning, therefore, they came as thick as -leaves and bloom in summer, and the hand of heaven was against us, so -that we were hard pressed. They set the battle in array near the ships, -and the hosts aimed their bronze-shod spears at one another.76 So long -as the day waxed and it was still morning, we held our own against -them, though they were more in number than we; but as the sun went -down, towards the time when men loose their oxen, the Cicons got the -better of us, and we lost half a dozen men from every ship we had; so -we got away with those that were left. - -“Thence we sailed onward with sorrow in our hearts, but glad to have -escaped death though we had lost our comrades, nor did we leave till we -had thrice invoked each one of the poor fellows who had perished by the -hands of the Cicons. Then Jove raised the North wind against us till it -blew a hurricane, so that land and sky were hidden in thick clouds, and -night sprang forth out of the heavens. We let the ships run before the -gale, but the force of the wind tore our sails to tatters, so we took -them down for fear of shipwreck, and rowed our hardest towards the -land. There we lay two days and two nights suffering much alike from -toil and distress of mind, but on the morning of the third day we again -raised our masts, set sail, and took our places, letting the wind and -steersmen direct our ship. I should have got home at that time unharmed -had not the North wind and the currents been against me as I was -doubling Cape Malea, and set me off my course hard by the island of -Cythera. - -“I was driven thence by foul winds for a space of nine days upon the -sea, but on the tenth day we reached the land of the Lotus-eaters, who -live on a food that comes from a kind of flower. Here we landed to take -in fresh water, and our crews got their mid-day meal on the shore near -the ships. When they had eaten and drunk I sent two of my company to -see what manner of men the people of the place might be, and they had a -third man under them. They started at once, and went about among the -Lotus-eaters, who did them no hurt, but gave them to eat of the lotus, -which was so delicious that those who ate of it left off caring about -home, and did not even want to go back and say what had happened to -them, but were for staying and munching lotus77 with the Lotus-eaters -without thinking further of their return; nevertheless, though they -wept bitterly I forced them back to the ships and made them fast under -the benches. Then I told the rest to go on board at once, lest any of -them should taste of the lotus and leave off wanting to get home, so -they took their places and smote the grey sea with their oars. - -“We sailed hence, always in much distress, till we came to the land of -the lawless and inhuman Cyclopes. Now the Cyclopes neither plant nor -plough, but trust in providence, and live on such wheat, barley, and -grapes as grow wild without any kind of tillage, and their wild grapes -yield them wine as the sun and the rain may grow them. They have no -laws nor assemblies of the people, but live in caves on the tops of -high mountains; each is lord and master in his family, and they take no -account of their neighbours. - -“Now off their harbour there lies a wooded and fertile island not quite -close to the land of the Cyclopes, but still not far. It is over-run -with wild goats, that breed there in great numbers and are never -disturbed by foot of man; for sportsmen—who as a rule will suffer so -much hardship in forest or among mountain precipices—do not go there, -nor yet again is it ever ploughed or fed down, but it lies a wilderness -untilled and unsown from year to year, and has no living thing upon it -but only goats. For the Cyclopes have no ships, nor yet shipwrights who -could make ships for them; they cannot therefore go from city to city, -or sail over the sea to one another’s country as people who have ships -can do; if they had had these they would have colonised the island,78 -for it is a very good one, and would yield everything in due season. -There are meadows that in some places come right down to the sea shore, -well watered and full of luscious grass; grapes would do there -excellently; there is level land for ploughing, and it would always -yield heavily at harvest time, for the soil is deep. There is a good -harbour where no cables are wanted, nor yet anchors, nor need a ship be -moored, but all one has to do is to beach one’s vessel and stay there -till the wind becomes fair for putting out to sea again. At the head of -the harbour there is a spring of clear water coming out of a cave, and -there are poplars growing all round it. - -“Here we entered, but so dark was the night that some god must have -brought us in, for there was nothing whatever to be seen. A thick mist -hung all round our ships;79 the moon was hidden behind a mass of clouds -so that no one could have seen the island if he had looked for it, nor -were there any breakers to tell us we were close in shore before we -found ourselves upon the land itself; when, however, we had beached the -ships, we took down the sails, went ashore and camped upon the beach -till daybreak. - -“When the child of morning, rosy-fingered Dawn appeared, we admired the -island and wandered all over it, while the nymphs Jove’s daughters -roused the wild goats that we might get some meat for our dinner. On -this we fetched our spears and bows and arrows from the ships, and -dividing ourselves into three bands began to shoot the goats. Heaven -sent us excellent sport; I had twelve ships with me, and each ship got -nine goats, while my own ship had ten; thus through the livelong day to -the going down of the sun we ate and drank our fill, and we had plenty -of wine left, for each one of us had taken many jars full when we -sacked the city of the Cicons, and this had not yet run out. While we -were feasting we kept turning our eyes towards the land of the -Cyclopes, which was hard by, and saw the smoke of their stubble fires. -We could almost fancy we heard their voices and the bleating of their -sheep and goats, but when the sun went down and it came on dark, we -camped down upon the beach, and next morning I called a council. - -“‘Stay here, my brave fellows,’ said I, ‘all the rest of you, while I -go with my ship and exploit these people myself: I want to see if they -are uncivilised savages, or a hospitable and humane race.’ - -“I went on board, bidding my men to do so also and loose the hawsers; -so they took their places and smote the grey sea with their oars. When -we got to the land, which was not far, there, on the face of a cliff -near the sea, we saw a great cave overhung with laurels. It was a -station for a great many sheep and goats, and outside there was a large -yard, with a high wall round it made of stones built into the ground -and of trees both pine and oak. This was the abode of a huge monster -who was then away from home shepherding his flocks. He would have -nothing to do with other people, but led the life of an outlaw. He was -a horrid creature, not like a human being at all, but resembling rather -some crag that stands out boldly against the sky on the top of a high -mountain. - -“I told my men to draw the ship ashore, and stay where they were, all -but the twelve best among them, who were to go along with myself. I -also took a goatskin of sweet black wine which had been given me by -Maron, son of Euanthes, who was priest of Apollo the patron god of -Ismarus, and lived within the wooded precincts of the temple. When we -were sacking the city we respected him, and spared his life, as also -his wife and child; so he made me some presents of great value—seven -talents of fine gold, and a bowl of silver, with twelve jars of sweet -wine, unblended, and of the most exquisite flavour. Not a man nor maid -in the house knew about it, but only himself, his wife, and one -housekeeper: when he drank it he mixed twenty parts of water to one of -wine, and yet the fragrance from the mixing-bowl was so exquisite that -it was impossible to refrain from drinking. I filled a large skin with -this wine, and took a wallet full of provisions with me, for my mind -misgave me that I might have to deal with some savage who would be of -great strength, and would respect neither right nor law. - -“We soon reached his cave, but he was out shepherding, so we went -inside and took stock of all that we could see. His cheese-racks were -loaded with cheeses, and he had more lambs and kids than his pens could -hold. They were kept in separate flocks; first there were the hoggets, -then the oldest of the younger lambs and lastly the very young ones80 -all kept apart from one another; as for his dairy, all the vessels, -bowls, and milk pails into which he milked, were swimming with whey. -When they saw all this, my men begged me to let them first steal some -cheeses, and make off with them to the ship; they would then return, -drive down the lambs and kids, put them on board and sail away with -them. It would have been indeed better if we had done so but I would -not listen to them, for I wanted to see the owner himself, in the hope -that he might give me a present. When, however, we saw him my poor men -found him ill to deal with. - -“We lit a fire, offered some of the cheeses in sacrifice, ate others of -them, and then sat waiting till the Cyclops should come in with his -sheep. When he came, he brought in with him a huge load of dry firewood -to light the fire for his supper, and this he flung with such a noise -on to the floor of his cave that we hid ourselves for fear at the far -end of the cavern. Meanwhile he drove all the ewes inside, as well as -the she-goats that he was going to milk, leaving the males, both rams -and he-goats, outside in the yards. Then he rolled a huge stone to the -mouth of the cave—so huge that two and twenty strong four-wheeled -waggons would not be enough to draw it from its place against the -doorway. When he had so done he sat down and milked his ewes and goats, -all in due course, and then let each of them have her own young. He -curdled half the milk and set it aside in wicker strainers, but the -other half he poured into bowls that he might drink it for his supper. -When he had got through with all his work, he lit the fire, and then -caught sight of us, whereon he said: - -“‘Strangers, who are you? Where do sail from? Are you traders, or do -you sail the sea as rovers, with your hands against every man, and -every man’s hand against you?’ - -“We were frightened out of our senses by his loud voice and monstrous -form, but I managed to say, ‘We are Achaeans on our way home from Troy, -but by the will of Jove, and stress of weather, we have been driven far -out of our course. We are the people of Agamemnon, son of Atreus, who -has won infinite renown throughout the whole world, by sacking so great -a city and killing so many people. We therefore humbly pray you to show -us some hospitality, and otherwise make us such presents as visitors -may reasonably expect. May your excellency fear the wrath of heaven, -for we are your suppliants, and Jove takes all respectable travellers -under his protection, for he is the avenger of all suppliants and -foreigners in distress.’ - -“To this he gave me but a pitiless answer, ‘Stranger,’ said he, ‘you -are a fool, or else you know nothing of this country. Talk to me, -indeed, about fearing the gods or shunning their anger? We Cyclopes do -not care about Jove or any of your blessed gods, for we are ever so -much stronger than they. I shall not spare either yourself or your -companions out of any regard for Jove, unless I am in the humour for -doing so. And now tell me where you made your ship fast when you came -on shore. Was it round the point, or is she lying straight off the -land?’ - -“He said this to draw me out, but I was too cunning to be caught in -that way, so I answered with a lie; ‘Neptune,’ said I, ‘sent my ship on -to the rocks at the far end of your country, and wrecked it. We were -driven on to them from the open sea, but I and those who are with me -escaped the jaws of death.’ - -“The cruel wretch vouchsafed me not one word of answer, but with a -sudden clutch he gripped up two of my men at once and dashed them down -upon the ground as though they had been puppies. Their brains were shed -upon the ground, and the earth was wet with their blood. Then he tore -them limb from limb and supped upon them. He gobbled them up like a -lion in the wilderness, flesh, bones, marrow, and entrails, without -leaving anything uneaten. As for us, we wept and lifted up our hands to -heaven on seeing such a horrid sight, for we did not know what else to -do; but when the Cyclops had filled his huge paunch, and had washed -down his meal of human flesh with a drink of neat milk, he stretched -himself full length upon the ground among his sheep, and went to sleep. -I was at first inclined to seize my sword, draw it, and drive it into -his vitals, but I reflected that if I did we should all certainly be -lost, for we should never be able to shift the stone which the monster -had put in front of the door. So we stayed sobbing and sighing where we -were till morning came. - -“When the child of morning, rosy-fingered dawn, appeared, he again lit -his fire, milked his goats and ewes, all quite rightly, and then let -each have her own young one; as soon as he had got through with all his -work, he clutched up two more of my men, and began eating them for his -morning’s meal. Presently, with the utmost ease, he rolled the stone -away from the door and drove out his sheep, but he at once put it back -again—as easily as though he were merely clapping the lid on to a -quiver full of arrows. As soon as he had done so he shouted, and cried -‘Shoo, shoo,’ after his sheep to drive them on to the mountain; so I -was left to scheme some way of taking my revenge and covering myself -with glory. - -“In the end I deemed it would be the best plan to do as follows: The -Cyclops had a great club which was lying near one of the sheep pens; it -was of green olive wood, and he had cut it intending to use it for a -staff as soon as it should be dry. It was so huge that we could only -compare it to the mast of a twenty-oared merchant vessel of large -burden, and able to venture out into open sea. I went up to this club -and cut off about six feet of it; I then gave this piece to the men and -told them to fine it evenly off at one end, which they proceeded to do, -and lastly I brought it to a point myself, charring the end in the fire -to make it harder. When I had done this I hid it under dung, which was -lying about all over the cave, and told the men to cast lots which of -them should venture along with myself to lift it and bore it into the -monster’s eye while he was asleep. The lot fell upon the very four whom -I should have chosen, and I myself made five. In the evening the wretch -came back from shepherding, and drove his flocks into the cave—this -time driving them all inside, and not leaving any in the yards; I -suppose some fancy must have taken him, or a god must have prompted him -to do so. As soon as he had put the stone back to its place against the -door, he sat down, milked his ewes and his goats all quite rightly, and -then let each have her own young one; when he had got through with all -this work, he gripped up two more of my men, and made his supper off -them. So I went up to him with an ivy-wood bowl of black wine in my -hands: - -“‘Look here, Cyclops,’ said I, you have been eating a great deal of -man’s flesh, so take this and drink some wine, that you may see what -kind of liquor we had on board my ship. I was bringing it to you as a -drink-offering, in the hope that you would take compassion upon me and -further me on my way home, whereas all you do is to go on ramping and -raving most intolerably. You ought to be ashamed of yourself; how can -you expect people to come see you any more if you treat them in this -way?’ - -“He then took the cup and drank. He was so delighted with the taste of -the wine that he begged me for another bowl full. ‘Be so kind,’ he -said, ‘as to give me some more, and tell me your name at once. I want -to make you a present that you will be glad to have. We have wine even -in this country, for our soil grows grapes and the sun ripens them, but -this drinks like Nectar and Ambrosia all in one.’ - -“I then gave him some more; three times did I fill the bowl for him, -and three times did he drain it without thought or heed; then, when I -saw that the wine had got into his head, I said to him as plausibly as -I could: ‘Cyclops, you ask my name and I will tell it you; give me, -therefore, the present you promised me; my name is Noman; this is what -my father and mother and my friends have always called me.’ - -“But the cruel wretch said, ‘Then I will eat all Noman’s comrades -before Noman himself, and will keep Noman for the last. This is the -present that I will make him.’ - -“As he spoke he reeled, and fell sprawling face upwards on the ground. -His great neck hung heavily backwards and a deep sleep took hold upon -him. Presently he turned sick, and threw up both wine and the gobbets -of human flesh on which he had been gorging, for he was very drunk. -Then I thrust the beam of wood far into the embers to heat it, and -encouraged my men lest any of them should turn faint-hearted. When the -wood, green though it was, was about to blaze, I drew it out of the -fire glowing with heat, and my men gathered round me, for heaven had -filled their hearts with courage. We drove the sharp end of the beam -into the monster’s eye, and bearing upon it with all my weight I kept -turning it round and round as though I were boring a hole in a ship’s -plank with an auger, which two men with a wheel and strap can keep on -turning as long as they choose. Even thus did we bore the red hot beam -into his eye, till the boiling blood bubbled all over it as we worked -it round and round, so that the steam from the burning eyeball scalded -his eyelids and eyebrows, and the roots of the eye sputtered in the -fire. As a blacksmith plunges an axe or hatchet into cold water to -temper it—for it is this that gives strength to the iron—and it makes a -great hiss as he does so, even thus did the Cyclops’ eye hiss round the -beam of olive wood, and his hideous yells made the cave ring again. We -ran away in a fright, but he plucked the beam all besmirched with gore -from his eye, and hurled it from him in a frenzy of rage and pain, -shouting as he did so to the other Cyclopes who lived on the bleak -headlands near him; so they gathered from all quarters round his cave -when they heard him crying, and asked what was the matter with him. - -“‘What ails you, Polyphemus,’ said they, ‘that you make such a noise, -breaking the stillness of the night, and preventing us from being able -to sleep? Surely no man is carrying off your sheep? Surely no man is -trying to kill you either by fraud or by force?’ - -“But Polyphemus shouted to them from inside the cave, ‘Noman is killing -me by fraud; no man is killing me by force.’ - -“‘Then,’ said they, ‘if no man is attacking you, you must be ill; when -Jove makes people ill, there is no help for it, and you had better pray -to your father Neptune.’ - -“Then they went away, and I laughed inwardly at the success of my -clever stratagem, but the Cyclops, groaning and in an agony of pain, -felt about with his hands till he found the stone and took it from the -door; then he sat in the doorway and stretched his hands in front of it -to catch anyone going out with the sheep, for he thought I might be -foolish enough to attempt this. - -“As for myself I kept on puzzling to think how I could best save my own -life and those of my companions; I schemed and schemed, as one who -knows that his life depends upon it, for the danger was very great. In -the end I deemed that this plan would be the best; the male sheep were -well grown, and carried a heavy black fleece, so I bound them -noiselessly in threes together, with some of the withies on which the -wicked monster used to sleep. There was to be a man under the middle -sheep, and the two on either side were to cover him, so that there were -three sheep to each man. As for myself there was a ram finer than any -of the others, so I caught hold of him by the back, esconced myself in -the thick wool under his belly, and hung on patiently to his fleece, -face upwards, keeping a firm hold on it all the time. - -“Thus, then, did we wait in great fear of mind till morning came, but -when the child of morning, rosy-fingered Dawn, appeared, the male sheep -hurried out to feed, while the ewes remained bleating about the pens -waiting to be milked, for their udders were full to bursting; but their -master in spite of all his pain felt the backs of all the sheep as they -stood upright, without being sharp enough to find out that the men were -underneath their bellies. As the ram was going out, last of all, heavy -with its fleece and with the weight of my crafty self, Polyphemus laid -hold of it and said: - -“‘My good ram, what is it that makes you the last to leave my cave this -morning? You are not wont to let the ewes go before you, but lead the -mob with a run whether to flowery mead or bubbling fountain, and are -the first to come home again at night; but now you lag last of all. Is -it because you know your master has lost his eye, and are sorry because -that wicked Noman and his horrid crew has got him down in his drink and -blinded him? But I will have his life yet. If you could understand and -talk, you would tell me where the wretch is hiding, and I would dash -his brains upon the ground till they flew all over the cave. I should -thus have some satisfaction for the harm this no-good Noman has done -me.’ - -“As he spoke he drove the ram outside, but when we were a little way -out from the cave and yards, I first got from under the ram’s belly, -and then freed my comrades; as for the sheep, which were very fat, by -constantly heading them in the right direction we managed to drive them -down to the ship. The crew rejoiced greatly at seeing those of us who -had escaped death, but wept for the others whom the Cyclops had killed. -However, I made signs to them by nodding and frowning that they were to -hush their crying, and told them to get all the sheep on board at once -and put out to sea; so they went aboard, took their places, and smote -the grey sea with their oars. Then, when I had got as far out as my -voice would reach, I began to jeer at the Cyclops. - -“‘Cyclops,’ said I, ‘you should have taken better measure of your man -before eating up his comrades in your cave. You wretch, eat up your -visitors in your own house? You might have known that your sin would -find you out, and now Jove and the other gods have punished you.’ - -“He got more and more furious as he heard me, so he tore the top from -off a high mountain, and flung it just in front of my ship so that it -was within a little of hitting the end of the rudder.81 The sea quaked -as the rock fell into it, and the wash of the wave it raised carried us -back towards the mainland, and forced us towards the shore. But I -snatched up a long pole and kept the ship off, making signs to my men -by nodding my head, that they must row for their lives, whereon they -laid out with a will. When we had got twice as far as we were before, I -was for jeering at the Cyclops again, but the men begged and prayed of -me to hold my tongue. - -“‘Do not,’ they exclaimed, ‘be mad enough to provoke this savage -creature further; he has thrown one rock at us already which drove us -back again to the mainland, and we made sure it had been the death of -us; if he had then heard any further sound of voices he would have -pounded our heads and our ship’s timbers into a jelly with the rugged -rocks he would have heaved at us, for he can throw them a long way.’ - -“But I would not listen to them, and shouted out to him in my rage, -‘Cyclops, if any one asks you who it was that put your eye out and -spoiled your beauty, say it was the valiant warrior Ulysses, son of -Laertes, who lives in Ithaca.’ - -“On this he groaned, and cried out, ‘Alas, alas, then the old prophecy -about me is coming true. There was a prophet here, at one time, a man -both brave and of great stature, Telemus son of Eurymus, who was an -excellent seer, and did all the prophesying for the Cyclopes till he -grew old; he told me that all this would happen to me some day, and -said I should lose my sight by the hand of Ulysses. I have been all -along expecting some one of imposing presence and superhuman strength, -whereas he turns out to be a little insignificant weakling, who has -managed to blind my eye by taking advantage of me in my drink; come -here, then, Ulysses, that I may make you presents to show my -hospitality, and urge Neptune to help you forward on your journey—for -Neptune and I are father and son. He, if he so will, shall heal me, -which no one else neither god nor man can do.’ - -“Then I said, ‘I wish I could be as sure of killing you outright and -sending you down to the house of Hades, as I am that it will take more -than Neptune to cure that eye of yours.’ - -“On this he lifted up his hands to the firmament of heaven and prayed, -saying, ‘Hear me, great Neptune; if I am indeed your own true begotten -son, grant that Ulysses may never reach his home alive; or if he must -get back to his friends at last, let him do so late and in sore plight -after losing all his men [let him reach his home in another man’s ship -and find trouble in his house.’82 - -“Thus did he pray, and Neptune heard his prayer. Then he picked up a -rock much larger than the first, swung it aloft and hurled it with -prodigious force. It fell just short of the ship, but was within a -little of hitting the end of the rudder. The sea quaked as the rock -fell into it, and the wash of the wave it raised drove us onwards on -our way towards the shore of the island. - -“When at last we got to the island where we had left the rest of our -ships, we found our comrades lamenting us, and anxiously awaiting our -return. We ran our vessel upon the sands and got out of her on to the -sea shore; we also landed the Cyclops’ sheep, and divided them -equitably amongst us so that none might have reason to complain. As for -the ram, my companions agreed that I should have it as an extra share; -so I sacrificed it on the sea shore, and burned its thigh bones to -Jove, who is the lord of all. But he heeded not my sacrifice, and only -thought how he might destroy both my ships and my comrades. - -“Thus through the livelong day to the going down of the sun we feasted -our fill on meat and drink, but when the sun went down and it came on -dark, we camped upon the beach. When the child of morning rosy-fingered -Dawn appeared, I bade my men on board and loose the hawsers. Then they -took their places and smote the grey sea with their oars; so we sailed -on with sorrow in our hearts, but glad to have escaped death though we -had lost our comrades. - - - - -BOOK X - - -AEOLUS, THE LAESTRYGONES, CIRCE. - - -“Thence we went on to the Aeolian island where lives Aeolus son of -Hippotas, dear to the immortal gods. It is an island that floats (as it -were) upon the sea,83 iron bound with a wall that girds it. Now, Aeolus -has six daughters and six lusty sons, so he made the sons marry the -daughters, and they all live with their dear father and mother, -feasting and enjoying every conceivable kind of luxury. All day long -the atmosphere of the house is loaded with the savour of roasting meats -till it groans again, yard and all; but by night they sleep on their -well made bedsteads, each with his own wife between the blankets. These -were the people among whom we had now come. - -“Aeolus entertained me for a whole month asking me questions all the -time about Troy, the Argive fleet, and the return of the Achaeans. I -told him exactly how everything had happened, and when I said I must -go, and asked him to further me on my way, he made no sort of -difficulty, but set about doing so at once. Moreover, he flayed me a -prime ox-hide to hold the ways of the roaring winds, which he shut up -in the hide as in a sack—for Jove had made him captain over the winds, -and he could stir or still each one of them according to his own -pleasure. He put the sack in the ship and bound the mouth so tightly -with a silver thread that not even a breath of a side-wind could blow -from any quarter. The West wind which was fair for us did he alone let -blow as it chose; but it all came to nothing, for we were lost through -our own folly. - -“Nine days and nine nights did we sail, and on the tenth day our native -land showed on the horizon. We got so close in that we could see the -stubble fires burning, and I, being then dead beat, fell into a light -sleep, for I had never let the rudder out of my own hands, that we -might get home the faster. On this the men fell to talking among -themselves, and said I was bringing back gold and silver in the sack -that Aeolus had given me. ‘Bless my heart,’ would one turn to his -neighbour, saying, ‘how this man gets honoured and makes friends to -whatever city or country he may go. See what fine prizes he is taking -home from Troy, while we, who have travelled just as far as he has, -come back with hands as empty as we set out with—and now Aeolus has -given him ever so much more. Quick—let us see what it all is, and how -much gold and silver there is in the sack he gave him.’ - -“Thus they talked and evil counsels prevailed. They loosed the sack, -whereupon the wind flew howling forth and raised a storm that carried -us weeping out to sea and away from our own country. Then I awoke, and -knew not whether to throw myself into the sea or to live on and make -the best of it; but I bore it, covered myself up, and lay down in the -ship, while the men lamented bitterly as the fierce winds bore our -fleet back to the Aeolian island. - -“When we reached it we went ashore to take in water, and dined hard by -the ships. Immediately after dinner I took a herald and one of my men -and went straight to the house of Aeolus, where I found him feasting -with his wife and family; so we sat down as suppliants on the -threshold. They were astounded when they saw us and said, ‘Ulysses, -what brings you here? What god has been ill-treating you? We took great -pains to further you on your way home to Ithaca, or wherever it was -that you wanted to go to.’ - -“Thus did they speak, but I answered sorrowfully, ‘My men have undone -me; they, and cruel sleep, have ruined me. My friends, mend me this -mischief, for you can if you will.’ - -“I spoke as movingly as I could, but they said nothing, till their -father answered, ‘Vilest of mankind, get you gone at once out of the -island; him whom heaven hates will I in no wise help. Be off, for you -come here as one abhorred of heaven.’ And with these words he sent me -sorrowing from his door. - -“Thence we sailed sadly on till the men were worn out with long and -fruitless rowing, for there was no longer any wind to help them. Six -days, night and day did we toil, and on the seventh day we reached the -rocky stronghold of Lamus—Telepylus, the city of the Laestrygonians, -where the shepherd who is driving in his sheep and goats [to be milked] -salutes him who is driving out his flock [to feed] and this last -answers the salute. In that country a man who could do without sleep -might earn double wages, one as a herdsman of cattle, and another as a -shepherd, for they work much the same by night as they do by day.84 - -“When we reached the harbour we found it land-locked under steep -cliffs, with a narrow entrance between two headlands. My captains took -all their ships inside, and made them fast close to one another, for -there was never so much as a breath of wind inside, but it was always -dead calm. I kept my own ship outside, and moored it to a rock at the -very end of the point; then I climbed a high rock to reconnoitre, but -could see no sign neither of man nor cattle, only some smoke rising -from the ground. So I sent two of my company with an attendant to find -out what sort of people the inhabitants were. - -“The men when they got on shore followed a level road by which the -people draw their firewood from the mountains into the town, till -presently they met a young woman who had come outside to fetch water, -and who was daughter to a Laestrygonian named Antiphates. She was going -to the fountain Artacia from which the people bring in their water, and -when my men had come close up to her, they asked her who the king of -that country might be, and over what kind of people he ruled; so she -directed them to her father’s house, but when they got there they found -his wife to be a giantess as huge as a mountain, and they were -horrified at the sight of her. - -“She at once called her husband Antiphates from the place of assembly, -and forthwith he set about killing my men. He snatched up one of them, -and began to make his dinner off him then and there, whereon the other -two ran back to the ships as fast as ever they could. But Antiphates -raised a hue-and-cry after them, and thousands of sturdy Laestrygonians -sprang up from every quarter—ogres, not men. They threw vast rocks at -us from the cliffs as though they had been mere stones, and I heard the -horrid sound of the ships crunching up against one another, and the -death cries of my men, as the Laestrygonians speared them like fishes -and took them home to eat them. While they were thus killing my men -within the harbour I drew my sword, cut the cable of my own ship, and -told my men to row with all their might if they too would not fare like -the rest; so they laid out for their lives, and we were thankful enough -when we got into open water out of reach of the rocks they hurled at -us. As for the others there was not one of them left. - -“Thence we sailed sadly on, glad to have escaped death, though we had -lost our comrades, and came to the Aeaean island, where Circe lives—a -great and cunning goddess who is own sister to the magician Aeetes—for -they are both children of the sun by Perse, who is daughter to Oceanus. -We brought our ship into a safe harbour without a word, for some god -guided us thither, and having landed we lay there for two days and two -nights, worn out in body and mind. When the morning of the third day -came I took my spear and my sword, and went away from the ship to -reconnoitre, and see if I could discover signs of human handiwork, or -hear the sound of voices. Climbing to the top of a high look-out I -espied the smoke of Circe’s house rising upwards amid a dense forest of -trees, and when I saw this I doubted whether, having seen the smoke, I -would not go on at once and find out more, but in the end I deemed it -best to go back to the ship, give the men their dinners, and send some -of them instead of going myself. - -“When I had nearly got back to the ship some god took pity upon my -solitude, and sent a fine antlered stag right into the middle of my -path. He was coming down his pasture in the forest to drink of the -river, for the heat of the sun drove him, and as he passed I struck him -in the middle of the back; the bronze point of the spear went clean -through him, and he lay groaning in the dust until the life went out of -him. Then I set my foot upon him, drew my spear from the wound, and -laid it down; I also gathered rough grass and rushes and twisted them -into a fathom or so of good stout rope, with which I bound the four -feet of the noble creature together; having so done I hung him round my -neck and walked back to the ship leaning upon my spear, for the stag -was much too big for me to be able to carry him on my shoulder, -steadying him with one hand. As I threw him down in front of the ship, -I called the men and spoke cheeringly man by man to each of them. ‘Look -here my friends,’ said I, ‘we are not going to die so much before our -time after all, and at any rate we will not starve so long as we have -got something to eat and drink on board.’ On this they uncovered their -heads upon the sea shore and admired the stag, for he was indeed a -splendid fellow. Then, when they had feasted their eyes upon him -sufficiently, they washed their hands and began to cook him for dinner. - -“Thus through the livelong day to the going down of the sun we stayed -there eating and drinking our fill, but when the sun went down and it -came on dark, we camped upon the sea shore. When the child of morning, -rosy-fingered Dawn, appeared, I called a council and said, ‘My friends, -we are in very great difficulties; listen therefore to me. We have no -idea where the sun either sets or rises,85 so that we do not even know -East from West. I see no way out of it; nevertheless, we must try and -find one. We are certainly on an island, for I went as high as I could -this morning, and saw the sea reaching all round it to the horizon; it -lies low, but towards the middle I saw smoke rising from out of a thick -forest of trees.’ - -“Their hearts sank as they heard me, for they remembered how they had -been treated by the Laestrygonian Antiphates, and by the savage ogre -Polyphemus. They wept bitterly in their dismay, but there was nothing -to be got by crying, so I divided them into two companies and set a -captain over each; I gave one company to Eurylochus, while I took -command of the other myself. Then we cast lots in a helmet, and the lot -fell upon Eurylochus; so he set out with his twenty-two men, and they -wept, as also did we who were left behind. - -“When they reached Circe’s house they found it built of cut stones, on -a site that could be seen from far, in the middle of the forest. There -were wild mountain wolves and lions prowling all round it—poor -bewitched creatures whom she had tamed by her enchantments and drugged -into subjection. They did not attack my men, but wagged their great -tails, fawned upon them, and rubbed their noses lovingly against -them.86 As hounds crowd round their master when they see him coming -from dinner—for they know he will bring them something—even so did -these wolves and lions with their great claws fawn upon my men, but the -men were terribly frightened at seeing such strange creatures. -Presently they reached the gates of the goddess’s house, and as they -stood there they could hear Circe within, singing most beautifully as -she worked at her loom, making a web so fine, so soft, and of such -dazzling colours as no one but a goddess could weave. On this Polites, -whom I valued and trusted more than any other of my men, said, ‘There -is some one inside working at a loom and singing most beautifully; the -whole place resounds with it, let us call her and see whether she is -woman or goddess.’ - -“They called her and she came down, unfastened the door, and bade them -enter. They, thinking no evil, followed her, all except Eurylochus, who -suspected mischief and staid outside. When she had got them into her -house, she set them upon benches and seats and mixed them a mess with -cheese, honey, meal, and Pramnian wine, but she drugged it with wicked -poisons to make them forget their homes, and when they had drunk she -turned them into pigs by a stroke of her wand, and shut them up in her -pig-styes. They were like pigs—head, hair, and all, and they grunted -just as pigs do; but their senses were the same as before, and they -remembered everything. - -“Thus then were they shut up squealing, and Circe threw them some -acorns and beech masts such as pigs eat, but Eurylochus hurried back to -tell me about the sad fate of our comrades. He was so overcome with -dismay that though he tried to speak he could find no words to do so; -his eyes filled with tears and he could only sob and sigh, till at last -we forced his story out of him, and he told us what had happened to the -others. - -“‘We went,’ said he, ‘as you told us, through the forest, and in the -middle of it there was a fine house built with cut stones in a place -that could be seen from far. There we found a woman, or else she was a -goddess, working at her loom and singing sweetly; so the men shouted to -her and called her, whereon she at once came down, opened the door, and -invited us in. The others did not suspect any mischief so they followed -her into the house, but I staid where I was, for I thought there might -be some treachery. From that moment I saw them no more, for not one of -them ever came out, though I sat a long time watching for them.’ - -“Then I took my sword of bronze and slung it over my shoulders; I also -took my bow, and told Eurylochus to come back with me and shew me the -way. But he laid hold of me with both his hands and spoke piteously, -saying, ‘Sir, do not force me to go with you, but let me stay here, for -I know you will not bring one of them back with you, nor even return -alive yourself; let us rather see if we cannot escape at any rate with -the few that are left us, for we may still save our lives.’ - -“‘Stay where you are, then,’ answered I, ‘eating and drinking at the -ship, but I must go, for I am most urgently bound to do so.’ - -“With this I left the ship and went up inland. When I got through the -charmed grove, and was near the great house of the enchantress Circe, I -met Mercury with his golden wand, disguised as a young man in the -hey-day of his youth and beauty with the down just coming upon his -face. He came up to me and took my hand within his own, saying, ‘My -poor unhappy man, whither are you going over this mountain top, alone -and without knowing the way? Your men are shut up in Circe’s pigstyes, -like so many wild boars in their lairs. You surely do not fancy that -you can set them free? I can tell you that you will never get back and -will have to stay there with the rest of them. But never mind, I will -protect you and get you out of your difficulty. Take this herb, which -is one of great virtue, and keep it about you when you go to Circe’s -house, it will be a talisman to you against every kind of mischief. - -“‘And I will tell you of all the wicked witchcraft that Circe will try -to practice upon you. She will mix a mess for you to drink, and she -will drug the meal with which she makes it, but she will not be able to -charm you, for the virtue of the herb that I shall give you will -prevent her spells from working. I will tell you all about it. When -Circe strikes you with her wand, draw your sword and spring upon her as -though you were going to kill her. She will then be frightened, and -will desire you to go to bed with her; on this you must not point blank -refuse her, for you want her to set your companions free, and to take -good care also of yourself, but you must make her swear solemnly by all -the blessed gods that she will plot no further mischief against you, or -else when she has got you naked she will unman you and make you fit for -nothing.’ - -“As he spoke he pulled the herb out of the ground and shewed me what it -was like. The root was black, while the flower was as white as milk; -the gods call it Moly, and mortal men cannot uproot it, but the gods -can do whatever they like. - -“Then Mercury went back to high Olympus passing over the wooded island; -but I fared onward to the house of Circe, and my heart was clouded with -care as I walked along. When I got to the gates I stood there and -called the goddess, and as soon as she heard me she came down, opened -the door, and asked me to come in; so I followed her—much troubled in -my mind. She set me on a richly decorated seat inlaid with silver, -there was a footstool also under my feet, and she mixed a mess in a -golden goblet for me to drink; but she drugged it, for she meant me -mischief. When she had given it me, and I had drunk it without its -charming me, she struck me with her wand. ‘There now,’ she cried, ‘be -off to the pigstye, and make your lair with the rest of them.’ - -“But I rushed at her with my sword drawn as though I would kill her, -whereon she fell with a loud scream, clasped my knees, and spoke -piteously, saying, ‘Who and whence are you? from what place and people -have you come? How can it be that my drugs have no power to charm you? -Never yet was any man able to stand so much as a taste of the herb I -gave you; you must be spell-proof; surely you can be none other than -the bold hero Ulysses, who Mercury always said would come here some day -with his ship while on his way home from Troy; so be it then; sheathe -your sword and let us go to bed, that we may make friends and learn to -trust each other.’ - -“And I answered, ‘Circe, how can you expect me to be friendly with you -when you have just been turning all my men into pigs? And now that you -have got me here myself, you mean me mischief when you ask me to go to -bed with you, and will unman me and make me fit for nothing. I shall -certainly not consent to go to bed with you unless you will first take -your solemn oath to plot no further harm against me.’ - -“So she swore at once as I had told her, and when she had completed her -oath then I went to bed with her. - -“Meanwhile her four servants, who are her housemaids, set about their -work. They are the children of the groves and fountains, and of the -holy waters that run down into the sea. One of them spread a fair -purple cloth over a seat, and laid a carpet underneath it. Another -brought tables of silver up to the seats, and set them with baskets of -gold. A third mixed some sweet wine with water in a silver bowl and put -golden cups upon the tables, while the fourth brought in water and set -it to boil in a large cauldron over a good fire which she had lighted. -When the water in the cauldron was boiling,87 she poured cold into it -till it was just as I liked it, and then she set me in a bath and began -washing me from the cauldron about the head and shoulders, to take the -tire and stiffness out of my limbs. As soon as she had done washing me -and anointing me with oil, she arrayed me in a good cloak and shirt and -led me to a richly decorated seat inlaid with silver; there was a -footstool also under my feet. A maid servant then brought me water in a -beautiful golden ewer and poured it into a silver basin for me to wash -my hands, and she drew a clean table beside me; an upper servant -brought me bread and offered me many things of what there was in the -house, and then Circe bade me eat, but I would not, and sat without -heeding what was before me, still moody and suspicious. - -“When Circe saw me sitting there without eating, and in great grief, -she came to me and said, ‘Ulysses, why do you sit like that as though -you were dumb, gnawing at your own heart, and refusing both meat and -drink? Is it that you are still suspicious? You ought not to be, for I -have already sworn solemnly that I will not hurt you.’ - -“And I said, ‘Circe, no man with any sense of what is right can think -of either eating or drinking in your house until you have set his -friends free and let him see them. If you want me to eat and drink, you -must free my men and bring them to me that I may see them with my own -eyes.’ - -“When I had said this she went straight through the court with her wand -in her hand and opened the pigstye doors. My men came out like so many -prime hogs and stood looking at her, but she went about among them and -anointed each with a second drug, whereon the bristles that the bad -drug had given them fell off, and they became men again, younger than -they were before, and much taller and better looking. They knew me at -once, seized me each of them by the hand, and wept for joy till the -whole house was filled with the sound of their halloa-ballooing, and -Circe herself was so sorry for them that she came up to me and said, -‘Ulysses, noble son of Laertes, go back at once to the sea where you -have left your ship, and first draw it on to the land. Then, hide all -your ship’s gear and property in some cave, and come back here with -your men.’ - -“I agreed to this, so I went back to the sea shore, and found the men -at the ship weeping and wailing most piteously. When they saw me the -silly blubbering fellows began frisking round me as calves break out -and gambol round their mothers, when they see them coming home to be -milked after they have been feeding all day, and the homestead resounds -with their lowing. They seemed as glad to see me as though they had got -back to their own rugged Ithaca, where they had been born and bred. -‘Sir,’ said the affectionate creatures, ‘we are as glad to see you back -as though we had got safe home to Ithaca; but tell us all about the -fate of our comrades.’ - -“I spoke comfortingly to them and said, ‘We must draw our ship on to -the land, and hide the ship’s gear with all our property in some cave; -then come with me all of you as fast as you can to Circe’s house, where -you will find your comrades eating and drinking in the midst of great -abundance.’ - -“On this the men would have come with me at once, but Eurylochus tried -to hold them back and said, ‘Alas, poor wretches that we are, what will -become of us? Rush not on your ruin by going to the house of Circe, who -will turn us all into pigs or wolves or lions, and we shall have to -keep guard over her house. Remember how the Cyclops treated us when our -comrades went inside his cave, and Ulysses with them. It was all -through his sheer folly that those men lost their lives.’ - -“When I heard him I was in two minds whether or no to draw the keen -blade that hung by my sturdy thigh and cut his head off in spite of his -being a near relation of my own; but the men interceded for him and -said, ‘Sir, if it may so be, let this fellow stay here and mind the -ship, but take the rest of us with you to Circe’s house.’ - -“On this we all went inland, and Eurylochus was not left behind after -all, but came on too, for he was frightened by the severe reprimand -that I had given him. - -“Meanwhile Circe had been seeing that the men who had been left behind -were washed and anointed with olive oil; she had also given them -woollen cloaks and shirts, and when we came we found them all -comfortably at dinner in her house. As soon as the men saw each other -face to face and knew one another, they wept for joy and cried aloud -till the whole palace rang again. Thereon Circe came up to me and said, -‘Ulysses, noble son of Laertes, tell your men to leave off crying; I -know how much you have all of you suffered at sea, and how ill you have -fared among cruel savages on the mainland, but that is over now, so -stay here, and eat and drink till you are once more as strong and -hearty as you were when you left Ithaca; for at present you are -weakened both in body and mind; you keep all the time thinking of the -hardships you have suffered during your travels, so that you have no -more cheerfulness left in you.’ - -“Thus did she speak and we assented. We stayed with Circe for a whole -twelvemonth feasting upon an untold quantity both of meat and wine. But -when the year had passed in the waning of moons and the long days had -come round, my men called me apart and said, ‘Sir, it is time you began -to think about going home, if so be you are to be spared to see your -house and native country at all.’ - -“Thus did they speak and I assented. Thereon through the livelong day -to the going down of the sun we feasted our fill on meat and wine, but -when the sun went down and it came on dark the men laid themselves down -to sleep in the covered cloisters. I, however, after I had got into bed -with Circe, besought her by her knees, and the goddess listened to what -I had got to say. ‘Circe,’ said I, ‘please to keep the promise you made -me about furthering me on my homeward voyage. I want to get back and so -do my men, they are always pestering me with their complaints as soon -as ever your back is turned.’ - -“And the goddess answered, ‘Ulysses, noble son of Laertes, you shall -none of you stay here any longer if you do not want to, but there is -another journey which you have got to take before you can sail -homewards. You must go to the house of Hades and of dread Proserpine to -consult the ghost of the blind Theban prophet Teiresias, whose reason -is still unshaken. To him alone has Proserpine left his understanding -even in death, but the other ghosts flit about aimlessly.’ - -“I was dismayed when I heard this. I sat up in bed and wept, and would -gladly have lived no longer to see the light of the sun, but presently -when I was tired of weeping and tossing myself about, I said, ‘And who -shall guide me upon this voyage—for the house of Hades is a port that -no ship can reach.’ - -“‘You will want no guide,’ she answered; ‘raise your mast, set your -white sails, sit quite still, and the North Wind will blow you there of -itself. When your ship has traversed the waters of Oceanus, you will -reach the fertile shore of Proserpine’s country with its groves of tall -poplars and willows that shed their fruit untimely; here beach your -ship upon the shore of Oceanus, and go straight on to the dark abode of -Hades. You will find it near the place where the rivers Pyriphlegethon -and Cocytus (which is a branch of the river Styx) flow into Acheron, -and you will see a rock near it, just where the two roaring rivers run -into one another. - -“‘When you have reached this spot, as I now tell you, dig a trench a -cubit or so in length, breadth, and depth, and pour into it as a -drink-offering to all the dead, first, honey mixed with milk, then -wine, and in the third place water—sprinkling white barley meal over -the whole. Moreover you must offer many prayers to the poor feeble -ghosts, and promise them that when you get back to Ithaca you will -sacrifice a barren heifer to them, the best you have, and will load the -pyre with good things. More particularly you must promise that -Teiresias shall have a black sheep all to himself, the finest in all -your flocks. - -“‘When you shall have thus besought the ghosts with your prayers, offer -them a ram and a black ewe, bending their heads towards Erebus; but -yourself turn away from them as though you would make towards the -river. On this, many dead men’s ghosts will come to you, and you must -tell your men to skin the two sheep that you have just killed, and -offer them as a burnt sacrifice with prayers to Hades and to -Proserpine. Then draw your sword and sit there, so as to prevent any -other poor ghost from coming near the spilt blood before Teiresias -shall have answered your questions. The seer will presently come to -you, and will tell you about your voyage—what stages you are to make, -and how you are to sail the sea so as to reach your home.’ - -“It was day-break by the time she had done speaking, so she dressed me -in my shirt and cloak. As for herself she threw a beautiful light -gossamer fabric over her shoulders, fastening it with a golden girdle -round her waist, and she covered her head with a mantle. Then I went -about among the men everywhere all over the house, and spoke kindly to -each of them man by man: ‘You must not lie sleeping here any longer,’ -said I to them, ‘we must be going, for Circe has told me all about it.’ -And on this they did as I bade them. - -“Even so, however, I did not get them away without misadventure. We had -with us a certain youth named Elpenor, not very remarkable for sense or -courage, who had got drunk and was lying on the house-top away from the -rest of the men, to sleep off his liquor in the cool. When he heard the -noise of the men bustling about, he jumped up on a sudden and forgot -all about coming down by the main staircase, so he tumbled right off -the roof and broke his neck, and his soul went down to the house of -Hades. - -“When I had got the men together I said to them, ‘You think you are -about to start home again, but Circe has explained to me that instead -of this, we have got to go to the house of Hades and Proserpine to -consult the ghost of the Theban prophet Teiresias.’ - -“The men were broken-hearted as they heard me, and threw themselves on -the ground groaning and tearing their hair, but they did not mend -matters by crying. When we reached the sea shore, weeping and lamenting -our fate, Circe brought the ram and the ewe, and we made them fast hard -by the ship. She passed through the midst of us without our knowing it, -for who can see the comings and goings of a god, if the god does not -wish to be seen? - - - - -BOOK XI - - -THE VISIT TO THE DEAD.88 - - -“Then, when we had got down to the sea shore we drew our ship into the -water and got her mast and sails into her; we also put the sheep on -board and took our places, weeping and in great distress of mind. -Circe, that great and cunning goddess, sent us a fair wind that blew -dead aft and staid steadily with us keeping our sails all the time well -filled; so we did whatever wanted doing to the ship’s gear and let her -go as the wind and helmsman headed her. All day long her sails were -full as she held her course over the sea, but when the sun went down -and darkness was over all the earth, we got into the deep waters of the -river Oceanus, where lie the land and city of the Cimmerians who live -enshrouded in mist and darkness which the rays of the sun never pierce -neither at his rising nor as he goes down again out of the heavens, but -the poor wretches live in one long melancholy night. When we got there -we beached the ship, took the sheep out of her, and went along by the -waters of Oceanus till we came to the place of which Circe had told us. - -“Here Perimedes and Eurylochus held the victims, while I drew my sword -and dug the trench a cubit each way. I made a drink-offering to all the -dead, first with honey and milk, then with wine, and thirdly with -water, and I sprinkled white barley meal over the whole, praying -earnestly to the poor feckless ghosts, and promising them that when I -got back to Ithaca I would sacrifice a barren heifer for them, the best -I had, and would load the pyre with good things. I also particularly -promised that Teiresias should have a black sheep to himself, the best -in all my flocks. When I had prayed sufficiently to the dead, I cut the -throats of the two sheep and let the blood run into the trench, whereon -the ghosts came trooping up from Erebus—brides,89 young bachelors, old -men worn out with toil, maids who had been crossed in love, and brave -men who had been killed in battle, with their armour still smirched -with blood; they came from every quarter and flitted round the trench -with a strange kind of screaming sound that made me turn pale with -fear. When I saw them coming I told the men to be quick and flay the -carcasses of the two dead sheep and make burnt offerings of them, and -at the same time to repeat prayers to Hades and to Proserpine; but I -sat where I was with my sword drawn and would not let the poor feckless -ghosts come near the blood till Teiresias should have answered my -questions. - -“The first ghost that came was that of my comrade Elpenor, for he had -not yet been laid beneath the earth. We had left his body unwaked and -unburied in Circe’s house, for we had had too much else to do. I was -very sorry for him, and cried when I saw him: ‘Elpenor,’ said I, ‘how -did you come down here into this gloom and darkness? You have got here -on foot quicker than I have with my ship.’ - -“‘Sir,’ he answered with a groan, ‘it was all bad luck, and my own -unspeakable drunkenness. I was lying asleep on the top of Circe’s -house, and never thought of coming down again by the great staircase -but fell right off the roof and broke my neck, so my soul came down to -the house of Hades. And now I beseech you by all those whom you have -left behind you, though they are not here, by your wife, by the father -who brought you up when you were a child, and by Telemachus who is the -one hope of your house, do what I shall now ask you. I know that when -you leave this limbo you will again hold your ship for the Aeaean -island. Do not go thence leaving me unwaked and unburied behind you, or -I may bring heaven’s anger upon you; but burn me with whatever armour I -have, build a barrow for me on the sea shore, that may tell people in -days to come what a poor unlucky fellow I was, and plant over my grave -the oar I used to row with when I was yet alive and with my messmates.’ -And I said, ‘My poor fellow, I will do all that you have asked of me.’ - -“Thus, then, did we sit and hold sad talk with one another, I on the -one side of the trench with my sword held over the blood, and the ghost -of my comrade saying all this to me from the other side. Then came the -ghost of my dead mother Anticlea, daughter to Autolycus. I had left her -alive when I set out for Troy and was moved to tears when I saw her, -but even so, for all my sorrow I would not let her come near the blood -till I had asked my questions of Teiresias. - -“Then came also the ghost of Theban Teiresias, with his golden sceptre -in his hand. He knew me and said, ‘Ulysses, noble son of Laertes, why, -poor man, have you left the light of day and come down to visit the -dead in this sad place? Stand back from the trench and withdraw your -sword that I may drink of the blood and answer your questions truly.’ - -“So I drew back, and sheathed my sword, whereon when he had drank of -the blood he began with his prophecy. - -“‘You want to know,’ said he, ‘about your return home, but heaven will -make this hard for you. I do not think that you will escape the eye of -Neptune, who still nurses his bitter grudge against you for having -blinded his son. Still, after much suffering you may get home if you -can restrain yourself and your companions when your ship reaches the -Thrinacian island, where you will find the sheep and cattle belonging -to the sun, who sees and gives ear to everything. If you leave these -flocks unharmed and think of nothing but of getting home, you may yet -after much hardship reach Ithaca; but if you harm them, then I forewarn -you of the destruction both of your ship and of your men. Even though -you may yourself escape, you will return in bad plight after losing all -your men, [in another man’s ship, and you will find trouble in your -house, which will be overrun by high-handed people, who are devouring -your substance under the pretext of paying court and making presents to -your wife. - -“‘When you get home you will take your revenge on these suitors; and -after you have killed them by force or fraud in your own house, you -must take a well made oar and carry it on and on, till you come to a -country where the people have never heard of the sea and do not even -mix salt with their food, nor do they know anything about ships, and -oars that are as the wings of a ship. I will give you this certain -token which cannot escape your notice. A wayfarer will meet you and -will say it must be a winnowing shovel that you have got upon your -shoulder; on this you must fix the oar in the ground and sacrifice a -ram, a bull, and a boar to Neptune.90 Then go home and offer hecatombs -to all the gods in heaven one after the other. As for yourself, death -shall come to you from the sea, and your life shall ebb away very -gently when you are full of years and peace of mind, and your people -shall bless you. All that I have said will come true].’91 - -“‘This,’ I answered, ‘must be as it may please heaven, but tell me and -tell me and tell me true, I see my poor mother’s ghost close by us; she -is sitting by the blood without saying a word, and though I am her own -son she does not remember me and speak to me; tell me, Sir, how I can -make her know me.’ - -“‘That,’ said he, ‘I can soon do. Any ghost that you let taste of the -blood will talk with you like a reasonable being, but if you do not let -them have any blood they will go away again.’ - -“On this the ghost of Teiresias went back to the house of Hades, for -his prophecyings had now been spoken, but I sat still where I was until -my mother came up and tasted the blood. Then she knew me at once and -spoke fondly to me, saying, ‘My son, how did you come down to this -abode of darkness while you are still alive? It is a hard thing for the -living to see these places, for between us and them there are great and -terrible waters, and there is Oceanus, which no man can cross on foot, -but he must have a good ship to take him. Are you all this time trying -to find your way home from Troy, and have you never yet got back to -Ithaca nor seen your wife in your own house?’ - -“‘Mother,’ said I, ‘I was forced to come here to consult the ghost of -the Theban prophet Teiresias. I have never yet been near the Achaean -land nor set foot on my native country, and I have had nothing but one -long series of misfortunes from the very first day that I set out with -Agamemnon for Ilius, the land of noble steeds, to fight the Trojans. -But tell me, and tell me true, in what way did you die? Did you have a -long illness, or did heaven vouchsafe you a gentle easy passage to -eternity? Tell me also about my father, and the son whom I left behind -me, is my property still in their hands, or has some one else got hold -of it, who thinks that I shall not return to claim it? Tell me again -what my wife intends doing, and in what mind she is; does she live with -my son and guard my estate securely, or has she made the best match she -could and married again?’ - -“My mother answered, ‘Your wife still remains in your house, but she is -in great distress of mind and spends her whole time in tears both night -and day. No one as yet has got possession of your fine property, and -Telemachus still holds your lands undisturbed. He has to entertain -largely, as of course he must, considering his position as a -magistrate,92 and how every one invites him; your father remains at his -old place in the country and never goes near the town. He has no -comfortable bed nor bedding; in the winter he sleeps on the floor in -front of the fire with the men and goes about all in rags, but in -summer, when the warm weather comes on again, he lies out in the -vineyard on a bed of vine leaves thrown any how upon the ground. He -grieves continually about your never having come home, and suffers more -and more as he grows older. As for my own end it was in this wise: -heaven did not take me swiftly and painlessly in my own house, nor was -I attacked by any illness such as those that generally wear people out -and kill them, but my longing to know what you were doing and the force -of my affection for you—this it was that was the death of me.’93 - -“Then I tried to find some way of embracing my poor mother’s ghost. -Thrice I sprang towards her and tried to clasp her in my arms, but each -time she flitted from my embrace as it were a dream or phantom, and -being touched to the quick I said to her, ‘Mother, why do you not stay -still when I would embrace you? If we could throw our arms around one -another we might find sad comfort in the sharing of our sorrows even in -the house of Hades; does Proserpine want to lay a still further load of -grief upon me by mocking me with a phantom only?’ - -“‘My son,’ she answered, ‘most ill-fated of all mankind, it is not -Proserpine that is beguiling you, but all people are like this when -they are dead. The sinews no longer hold the flesh and bones together; -these perish in the fierceness of consuming fire as soon as life has -left the body, and the soul flits away as though it were a dream. Now, -however, go back to the light of day as soon as you can, and note all -these things that you may tell them to your wife hereafter.’ - -“Thus did we converse, and anon Proserpine sent up the ghosts of the -wives and daughters of all the most famous men. They gathered in crowds -about the blood, and I considered how I might question them severally. -In the end I deemed that it would be best to draw the keen blade that -hung by my sturdy thigh, and keep them from all drinking the blood at -once. So they came up one after the other, and each one as I questioned -her told me her race and lineage. - -“The first I saw was Tyro. She was daughter of Salmoneus and wife of -Cretheus the son of Aeolus.94 She fell in love with the river Enipeus -who is much the most beautiful river in the whole world. Once when she -was taking a walk by his side as usual, Neptune, disguised as her -lover, lay with her at the mouth of the river, and a huge blue wave -arched itself like a mountain over them to hide both woman and god, -whereon he loosed her virgin girdle and laid her in a deep slumber. -When the god had accomplished the deed of love, he took her hand in his -own and said, ‘Tyro, rejoice in all good will; the embraces of the gods -are not fruitless, and you will have fine twins about this time twelve -months. Take great care of them. I am Neptune, so now go home, but hold -your tongue and do not tell any one.’ - -“Then he dived under the sea, and she in due course bore Pelias and -Neleus, who both of them served Jove with all their might. Pelias was a -great breeder of sheep and lived in Iolcus, but the other lived in -Pylos. The rest of her children were by Cretheus, namely, Aeson, -Pheres, and Amythaon, who was a mighty warrior and charioteer. - -“Next to her I saw Antiope, daughter to Asopus, who could boast of -having slept in the arms of even Jove himself, and who bore him two -sons Amphion and Zethus. These founded Thebes with its seven gates, and -built a wall all round it; for strong though they were they could not -hold Thebes till they had walled it. - -“Then I saw Alcmena, the wife of Amphitryon, who also bore to Jove -indomitable Hercules; and Megara who was daughter to great King Creon, -and married the redoubtable son of Amphitryon. - -“I also saw fair Epicaste mother of king Oedipodes whose awful lot it -was to marry her own son without suspecting it. He married her after -having killed his father, but the gods proclaimed the whole story to -the world; whereon he remained king of Thebes, in great grief for the -spite the gods had borne him; but Epicaste went to the house of the -mighty jailor Hades, having hanged herself for grief, and the avenging -spirits haunted him as for an outraged mother—to his ruing bitterly -thereafter. - -“Then I saw Chloris, whom Neleus married for her beauty, having given -priceless presents for her. She was youngest daughter to Amphion son of -Iasus and king of Minyan Orchomenus, and was Queen in Pylos. She bore -Nestor, Chromius, and Periclymenus, and she also bore that marvellously -lovely woman Pero, who was wooed by all the country round; but Neleus -would only give her to him who should raid the cattle of Iphicles from -the grazing grounds of Phylace, and this was a hard task. The only man -who would undertake to raid them was a certain excellent seer,95 but -the will of heaven was against him, for the rangers of the cattle -caught him and put him in prison; nevertheless when a full year had -passed and the same season came round again, Iphicles set him at -liberty, after he had expounded all the oracles of heaven. Thus, then, -was the will of Jove accomplished. - -“And I saw Leda the wife of Tyndarus, who bore him two famous sons, -Castor breaker of horses, and Pollux the mighty boxer. Both these -heroes are lying under the earth, though they are still alive, for by a -special dispensation of Jove, they die and come to life again, each one -of them every other day throughout all time, and they have the rank of -gods. - -“After her I saw Iphimedeia wife of Aloeus who boasted the embrace of -Neptune. She bore two sons Otus and Ephialtes, but both were short -lived. They were the finest children that were ever born in this world, -and the best looking, Orion only excepted; for at nine years old they -were nine fathoms high, and measured nine cubits round the chest. They -threatened to make war with the gods in Olympus, and tried to set Mount -Ossa on the top of Mount Olympus, and Mount Pelion on the top of Ossa, -that they might scale heaven itself, and they would have done it too if -they had been grown up, but Apollo, son of Leto, killed both of them, -before they had got so much as a sign of hair upon their cheeks or -chin. - -“Then I saw Phaedra, and Procris, and fair Ariadne daughter of the -magician Minos, whom Theseus was carrying off from Crete to Athens, but -he did not enjoy her, for before he could do so Diana killed her in the -island of Dia on account of what Bacchus had said against her. - -“I also saw Maera and Clymene and hateful Eriphyle, who sold her own -husband for gold. But it would take me all night if I were to name -every single one of the wives and daughters of heroes whom I saw, and -it is time for me to go to bed, either on board ship with my crew, or -here. As for my escort, heaven and yourselves will see to it.” - -Here he ended, and the guests sat all of them enthralled and speechless -throughout the covered cloister. Then Arete said to them:— - -“What do you think of this man, O Phaeacians? Is he not tall and good -looking, and is he not clever? True, he is my own guest, but all of you -share in the distinction. Do not be in a hurry to send him away, nor -niggardly in the presents you make to one who is in such great need, -for heaven has blessed all of you with great abundance.” - -Then spoke the aged hero Echeneus who was one of the oldest men among -them, “My friends,” said he, “what our august queen has just said to us -is both reasonable and to the purpose, therefore be persuaded by it; -but the decision whether in word or deed rests ultimately with King -Alcinous.” - -“The thing shall be done,” exclaimed Alcinous, “as surely as I still -live and reign over the Phaeacians. Our guest is indeed very anxious to -get home, still we must persuade him to remain with us until to-morrow, -by which time I shall be able to get together the whole sum that I mean -to give him. As regards his escort it will be a matter for you all, and -mine above all others as the chief person among you.” - -And Ulysses answered, “King Alcinous, if you were to bid me to stay -here for a whole twelve months, and then speed me on my way, loaded -with your noble gifts, I should obey you gladly and it would redound -greatly to my advantage, for I should return fuller-handed to my own -people, and should thus be more respected and beloved by all who see me -when I get back to Ithaca.” - -“Ulysses,” replied Alcinous, “not one of us who sees you has any idea -that you are a charlatan or a swindler. I know there are many people -going about who tell such plausible stories that it is very hard to see -through them, but there is a style about your language which assures me -of your good disposition. Moreover you have told the story of your own -misfortunes, and those of the Argives, as though you were a practiced -bard; but tell me, and tell me true, whether you saw any of the mighty -heroes who went to Troy at the same time with yourself, and perished -there. The evenings are still at their longest, and it is not yet bed -time—go on, therefore, with your divine story, for I could stay here -listening till tomorrow morning, so long as you will continue to tell -us of your adventures.” - -“Alcinous,” answered Ulysses, “there is a time for making speeches, and -a time for going to bed; nevertheless, since you so desire, I will not -refrain from telling you the still sadder tale of those of my comrades -who did not fall fighting with the Trojans, but perished on their -return, through the treachery of a wicked woman. - -“When Proserpine had dismissed the female ghosts in all directions, the -ghost of Agamemnon son of Atreus came sadly up to me, surrounded by -those who had perished with him in the house of Aegisthus. As soon as -he had tasted the blood, he knew me, and weeping bitterly stretched out -his arms towards me to embrace me; but he had no strength nor substance -any more, and I too wept and pitied him as I beheld him. ‘How did you -come by your death,’ said I, ‘King Agamemnon? Did Neptune raise his -winds and waves against you when you were at sea, or did your enemies -make an end of you on the main land when you were cattle-lifting or -sheep-stealing, or while they were fighting in defence of their wives -and city?’ - -“‘Ulysses,’ he answered, ‘noble son of Laertes, I was not lost at sea -in any storm of Neptune’s raising, nor did my foes despatch me upon the -mainland, but Aegisthus and my wicked wife were the death of me between -them. He asked me to his house, feasted me, and then butchered me most -miserably as though I were a fat beast in a slaughter house, while all -around me my comrades were slain like sheep or pigs for the wedding -breakfast, or picnic, or gorgeous banquet of some great nobleman. You -must have seen numbers of men killed either in a general engagement, or -in single combat, but you never saw anything so truly pitiable as the -way in which we fell in that cloister, with the mixing bowl and the -loaded tables lying all about, and the ground reeking with our blood. I -heard Priam’s daughter Cassandra scream as Clytemnestra killed her -close beside me. I lay dying upon the earth with the sword in my body, -and raised my hands to kill the slut of a murderess, but she slipped -away from me; she would not even close my lips nor my eyes when I was -dying, for there is nothing in this world so cruel and so shameless as -a woman when she has fallen into such guilt as hers was. Fancy -murdering her own husband! I thought I was going to be welcomed home by -my children and my servants, but her abominable crime has brought -disgrace on herself and all women who shall come after—even on the good -ones.’ - -“And I said, ‘In truth Jove has hated the house of Atreus from first to -last in the matter of their women’s counsels. See how many of us fell -for Helen’s sake, and now it seems that Clytemnestra hatched mischief -against you too during your absence.’ - -“‘Be sure, therefore,’ continued Agamemnon, ‘and not be too friendly -even with your own wife. Do not tell her all that you know perfectly -well yourself. Tell her a part only, and keep your own counsel about -the rest. Not that your wife, Ulysses, is likely to murder you, for -Penelope is a very admirable woman, and has an excellent nature. We -left her a young bride with an infant at her breast when we set out for -Troy. This child no doubt is now grown up happily to man’s estate,96 -and he and his father will have a joyful meeting and embrace one -another as it is right they should do, whereas my wicked wife did not -even allow me the happiness of looking upon my son, but killed me ere I -could do so. Furthermore I say—and lay my saying to your heart—do not -tell people when you are bringing your ship to Ithaca, but steal a -march upon them, for after all this there is no trusting women. But now -tell me, and tell me true, can you give me any news of my son Orestes? -Is he in Orchomenus, or at Pylos, or is he at Sparta with Menelaus—for -I presume that he is still living.’ - -“And I said, ‘Agamemnon, why do you ask me? I do not know whether your -son is alive or dead, and it is not right to talk when one does not -know.’ - -“As we two sat weeping and talking thus sadly with one another the -ghost of Achilles came up to us with Patroclus, Antilochus, and Ajax -who was the finest and goodliest man of all the Danaans after the son -of Peleus. The fleet descendant of Aeacus knew me and spoke piteously, -saying, ‘Ulysses, noble son of Laertes, what deed of daring will you -undertake next, that you venture down to the house of Hades among us -silly dead, who are but the ghosts of them that can labour no more?’ - -“And I said, ‘Achilles, son of Peleus, foremost champion of the -Achaeans, I came to consult Teiresias, and see if he could advise me -about my return home to Ithaca, for I have never yet been able to get -near the Achaean land, nor to set foot in my own country, but have been -in trouble all the time. As for you, Achilles, no one was ever yet so -fortunate as you have been, nor ever will be, for you were adored by -all us Argives as long as you were alive, and now that you are here you -are a great prince among the dead. Do not, therefore, take it so much -to heart even if you are dead.’ - -“‘Say not a word,’ he answered, ‘in death’s favour; I would rather be a -paid servant in a poor man’s house and be above ground than king of -kings among the dead. But give me news about my son; is he gone to the -wars and will he be a great soldier, or is this not so? Tell me also if -you have heard anything about my father Peleus—does he still rule among -the Myrmidons, or do they show him no respect throughout Hellas and -Phthia now that he is old and his limbs fail him? Could I but stand by -his side, in the light of day, with the same strength that I had when I -killed the bravest of our foes upon the plain of Troy—could I but be as -I then was and go even for a short time to my father’s house, any one -who tried to do him violence or supersede him would soon rue it.’ - -“‘I have heard nothing,’ I answered, ‘of Peleus, but I can tell you all -about your son Neoptolemus, for I took him in my own ship from Scyros -with the Achaeans. In our councils of war before Troy he was always -first to speak, and his judgement was unerring. Nestor and I were the -only two who could surpass him; and when it came to fighting on the -plain of Troy, he would never remain with the body of his men, but -would dash on far in front, foremost of them all in valour. Many a man -did he kill in battle—I cannot name every single one of those whom he -slew while fighting on the side of the Argives, but will only say how -he killed that valiant hero Eurypylus son of Telephus, who was the -handsomest man I ever saw except Memnon; many others also of the -Ceteians fell around him by reason of a woman’s bribes. Moreover, when -all the bravest of the Argives went inside the horse that Epeus had -made, and it was left to me to settle when we should either open the -door of our ambuscade, or close it, though all the other leaders and -chief men among the Danaans were drying their eyes and quaking in every -limb, I never once saw him turn pale nor wipe a tear from his cheek; he -was all the time urging me to break out from the horse—grasping the -handle of his sword and his bronze-shod spear, and breathing fury -against the foe. Yet when we had sacked the city of Priam he got his -handsome share of the prize money and went on board (such is the -fortune of war) without a wound upon him, neither from a thrown spear -nor in close combat, for the rage of Mars is a matter of great chance.’ - -“When I had told him this, the ghost of Achilles strode off across a -meadow full of asphodel, exulting over what I had said concerning the -prowess of his son. - -“The ghosts of other dead men stood near me and told me each his own -melancholy tale; but that of Ajax son of Telamon alone held aloof—still -angry with me for having won the cause in our dispute about the armour -of Achilles. Thetis had offered it as a prize, but the Trojan prisoners -and Minerva were the judges. Would that I had never gained the day in -such a contest, for it cost the life of Ajax, who was foremost of all -the Danaans after the son of Peleus, alike in stature and prowess. - -“When I saw him I tried to pacify him and said, ‘Ajax, will you not -forget and forgive even in death, but must the judgement about that -hateful armour still rankle with you? It cost us Argives dear enough to -lose such a tower of strength as you were to us. We mourned you as much -as we mourned Achilles son of Peleus himself, nor can the blame be laid -on anything but on the spite which Jove bore against the Danaans, for -it was this that made him counsel your destruction—come hither, -therefore, bring your proud spirit into subjection, and hear what I can -tell you.’ - -“He would not answer, but turned away to Erebus and to the other -ghosts; nevertheless, I should have made him talk to me in spite of his -being so angry, or I should have gone on talking to him,97 only that -there were still others among the dead whom I desired to see. - -“Then I saw Minos son of Jove with his golden sceptre in his hand -sitting in judgement on the dead, and the ghosts were gathered sitting -and standing round him in the spacious house of Hades, to learn his -sentences upon them. - -“After him I saw huge Orion in a meadow full of asphodel driving the -ghosts of the wild beasts that he had killed upon the mountains, and he -had a great bronze club in his hand, unbreakable for ever and ever. - -“And I saw Tityus son of Gaia stretched upon the plain and covering -some nine acres of ground. Two vultures on either side of him were -digging their beaks into his liver, and he kept on trying to beat them -off with his hands, but could not; for he had violated Jove’s mistress -Leto as she was going through Panopeus on her way to Pytho. - -“I saw also the dreadful fate of Tantalus, who stood in a lake that -reached his chin; he was dying to quench his thirst, but could never -reach the water, for whenever the poor creature stooped to drink, it -dried up and vanished, so that there was nothing but dry ground—parched -by the spite of heaven. There were tall trees, moreover, that shed -their fruit over his head—pears, pomegranates, apples, sweet figs and -juicy olives, but whenever the poor creature stretched out his hand to -take some, the wind tossed the branches back again to the clouds. - -“And I saw Sisyphus at his endless task raising his prodigious stone -with both his hands. With hands and feet he tried to roll it up to the -top of the hill, but always, just before he could roll it over on to -the other side, its weight would be too much for him, and the pitiless -stone98 would come thundering down again on to the plain. Then he would -begin trying to push it up hill again, and the sweat ran off him and -the steam rose after him. - -“After him I saw mighty Hercules, but it was his phantom only, for he -is feasting ever with the immortal gods, and has lovely Hebe to wife, -who is daughter of Jove and Juno. The ghosts were screaming round him -like scared birds flying all whithers. He looked black as night with -his bare bow in his hands and his arrow on the string, glaring around -as though ever on the point of taking aim. About his breast there was a -wondrous golden belt adorned in the most marvellous fashion with bears, -wild boars, and lions with gleaming eyes; there was also war, battle, -and death. The man who made that belt, do what he might, would never be -able to make another like it. Hercules knew me at once when he saw me, -and spoke piteously, saying, ‘My poor Ulysses, noble son of Laertes, -are you too leading the same sorry kind of life that I did when I was -above ground? I was son of Jove, but I went through an infinity of -suffering, for I became bondsman to one who was far beneath me—a low -fellow who set me all manner of labours. He once sent me here to fetch -the hell-hound—for he did not think he could find anything harder for -me than this, but I got the hound out of Hades and brought him to him, -for Mercury and Minerva helped me.’ - -“On this Hercules went down again into the house of Hades, but I stayed -where I was in case some other of the mighty dead should come to me. -And I should have seen still other of them that are gone before, whom I -would fain have seen—Theseus and Pirithous—glorious children of the -gods, but so many thousands of ghosts came round me and uttered such -appalling cries, that I was panic stricken lest Proserpine should send -up from the house of Hades the head of that awful monster Gorgon. On -this I hastened back to my ship and ordered my men to go on board at -once and loose the hawsers; so they embarked and took their places, -whereon the ship went down the stream of the river Oceanus. We had to -row at first, but presently a fair wind sprang up. - - - - -BOOK XII - - -THE SIRENS, SCYLLA AND CHARYBDIS, THE CATTLE OF THE SUN. - - -“After we were clear of the river Oceanus, and had got out into the -open sea, we went on till we reached the Aeaean island where there is -dawn and sun-rise as in other places. We then drew our ship on to the -sands and got out of her on to the shore, where we went to sleep and -waited till day should break. - -“Then, when the child of morning, rosy-fingered Dawn, appeared, I sent -some men to Circe’s house to fetch the body of Elpenor. We cut firewood -from a wood where the headland jutted out into the sea, and after we -had wept over him and lamented him we performed his funeral rites. When -his body and armour had been burned to ashes, we raised a cairn, set a -stone over it, and at the top of the cairn we fixed the oar that he had -been used to row with. - -“While we were doing all this, Circe, who knew that we had got back -from the house of Hades, dressed herself and came to us as fast as she -could; and her maid servants came with her bringing us bread, meat, and -wine. Then she stood in the midst of us and said, ‘You have done a bold -thing in going down alive to the house of Hades, and you will have died -twice, to other people’s once; now, then, stay here for the rest of the -day, feast your fill, and go on with your voyage at daybreak tomorrow -morning. In the meantime I will tell Ulysses about your course, and -will explain everything to him so as to prevent your suffering from -misadventure either by land or sea.’ - -“We agreed to do as she had said, and feasted through the livelong day -to the going down of the sun, but when the sun had set and it came on -dark, the men laid themselves down to sleep by the stern cables of the -ship. Then Circe took me by the hand and bade me be seated away from -the others, while she reclined by my side and asked me all about our -adventures. - -“‘So far so good,’ said she, when I had ended my story, ‘and now pay -attention to what I am about to tell you—heaven itself, indeed, will -recall it to your recollection. First you will come to the Sirens who -enchant all who come near them. If any one unwarily draws in too close -and hears the singing of the Sirens, his wife and children will never -welcome him home again, for they sit in a green field and warble him to -death with the sweetness of their song. There is a great heap of dead -men’s bones lying all around, with the flesh still rotting off them. -Therefore pass these Sirens by, and stop your men’s ears with wax that -none of them may hear; but if you like you can listen yourself, for you -may get the men to bind you as you stand upright on a cross piece half -way up the mast,99 and they must lash the rope’s ends to the mast -itself, that you may have the pleasure of listening. If you beg and -pray the men to unloose you, then they must bind you faster. - -“‘When your crew have taken you past these Sirens, I cannot give you -coherent directions100 as to which of two courses you are to take; I -will lay the two alternatives before you, and you must consider them -for yourself. On the one hand there are some overhanging rocks against -which the deep blue waves of Amphitrite beat with terrific fury; the -blessed gods call these rocks the Wanderers. Here not even a bird may -pass, no, not even the timid doves that bring ambrosia to Father Jove, -but the sheer rock always carries off one of them, and Father Jove has -to send another to make up their number; no ship that ever yet came to -these rocks has got away again, but the waves and whirlwinds of fire -are freighted with wreckage and with the bodies of dead men. The only -vessel that ever sailed and got through, was the famous Argo on her way -from the house of Aetes, and she too would have gone against these -great rocks, only that Juno piloted her past them for the love she bore -to Jason. - -“‘Of these two rocks the one reaches heaven and its peak is lost in a -dark cloud. This never leaves it, so that the top is never clear not -even in summer and early autumn. No man though he had twenty hands and -twenty feet could get a foothold on it and climb it, for it runs sheer -up, as smooth as though it had been polished. In the middle of it there -is a large cavern, looking West and turned towards Erebus; you must -take your ship this way, but the cave is so high up that not even the -stoutest archer could send an arrow into it. Inside it Scylla sits and -yelps with a voice that you might take to be that of a young hound, but -in truth she is a dreadful monster and no one—not even a god—could face -her without being terror-struck. She has twelve mis-shapen feet, and -six necks of the most prodigious length; and at the end of each neck -she has a frightful head with three rows of teeth in each, all set very -close together, so that they would crunch any one to death in a moment, -and she sits deep within her shady cell thrusting out her heads and -peering all round the rock, fishing for dolphins or dogfish or any -larger monster that she can catch, of the thousands with which -Amphitrite teems. No ship ever yet got past her without losing some -men, for she shoots out all her heads at once, and carries off a man in -each mouth. - -“‘You will find the other rock lie lower, but they are so close -together that there is not more than a bow-shot between them. [A large -fig tree in full leaf101 grows upon it], and under it lies the sucking -whirlpool of Charybdis. Three times in the day does she vomit forth her -waters, and three times she sucks them down again; see that you be not -there when she is sucking, for if you are, Neptune himself could not -save you; you must hug the Scylla side and drive ship by as fast as you -can, for you had better lose six men than your whole crew.’ - -“‘Is there no way,’ said I, ‘of escaping Charybdis, and at the same -time keeping Scylla off when she is trying to harm my men?’ - -“‘You dare devil,’ replied the goddess, ‘you are always wanting to -fight somebody or something; you will not let yourself be beaten even -by the immortals. For Scylla is not mortal; moreover she is savage, -extreme, rude, cruel and invincible. There is no help for it; your best -chance will be to get by her as fast as ever you can, for if you dawdle -about her rock while you are putting on your armour, she may catch you -with a second cast of her six heads, and snap up another half dozen of -your men; so drive your ship past her at full speed, and roar out -lustily to Crataiis who is Scylla’s dam, bad luck to her; she will then -stop her from making a second raid upon you.’ - -“‘You will now come to the Thrinacian island, and here you will see -many herds of cattle and flocks of sheep belonging to the sun-god—seven -herds of cattle and seven flocks of sheep, with fifty head in each -flock. They do not breed, nor do they become fewer in number, and they -are tended by the goddesses Phaethusa and Lampetie, who are children of -the sun-god Hyperion by Neaera. Their mother when she had borne them -and had done suckling them sent them to the Thrinacian island, which -was a long way off, to live there and look after their father’s flocks -and herds. If you leave these flocks unharmed, and think of nothing but -getting home, you may yet after much hardship reach Ithaca; but if you -harm them, then I forewarn you of the destruction both of your ship and -of your comrades; and even though you may yourself escape, you will -return late, in bad plight, after losing all your men.’ - -“Here she ended, and dawn enthroned in gold began to show in heaven, -whereon she returned inland. I then went on board and told my men to -loose the ship from her moorings; so they at once got into her, took -their places, and began to smite the grey sea with their oars. -Presently the great and cunning goddess Circe befriended us with a fair -wind that blew dead aft, and staid steadily with us, keeping our sails -well filled, so we did whatever wanted doing to the ship’s gear, and -let her go as wind and helmsman headed her. - -“Then, being much troubled in mind, I said to my men, ‘My friends, it -is not right that one or two of us alone should know the prophecies -that Circe has made me, I will therefore tell you about them, so that -whether we live or die we may do so with our eyes open. First she said -we were to keep clear of the Sirens, who sit and sing most beautifully -in a field of flowers; but she said I might hear them myself so long as -no one else did. Therefore, take me and bind me to the crosspiece half -way up the mast; bind me as I stand upright, with a bond so fast that I -cannot possibly break away, and lash the rope’s ends to the mast -itself. If I beg and pray you to set me free, then bind me more tightly -still.’ - -“I had hardly finished telling everything to the men before we reached -the island of the two Sirens,102 for the wind had been very favourable. -Then all of a sudden it fell dead calm; there was not a breath of wind -nor a ripple upon the water, so the men furled the sails and stowed -them; then taking to their oars they whitened the water with the foam -they raised in rowing. Meanwhile I look a large wheel of wax and cut it -up small with my sword. Then I kneaded the wax in my strong hands till -it became soft, which it soon did between the kneading and the rays of -the sun-god son of Hyperion. Then I stopped the ears of all my men, and -they bound me hands and feet to the mast as I stood upright on the -cross piece; but they went on rowing themselves. When we had got within -earshot of the land, and the ship was going at a good rate, the Sirens -saw that we were getting in shore and began with their singing. - -“‘Come here,’ they sang, ‘renowned Ulysses, honour to the Achaean name, -and listen to our two voices. No one ever sailed past us without -staying to hear the enchanting sweetness of our song—and he who listens -will go on his way not only charmed, but wiser, for we know all the -ills that the gods laid upon the Argives and Trojans before Troy, and -can tell you everything that is going to happen over the whole world.’ - -“They sang these words most musically, and as I longed to hear them -further I made signs by frowning to my men that they should set me -free; but they quickened their stroke, and Eurylochus and Perimedes -bound me with still stronger bonds till we had got out of hearing of -the Sirens’ voices. Then my men took the wax from their ears and -unbound me. - -“Immediately after we had got past the island I saw a great wave from -which spray was rising, and I heard a loud roaring sound. The men were -so frightened that they loosed hold of their oars, for the whole sea -resounded with the rushing of the waters,103 but the ship stayed where -it was, for the men had left off rowing. I went round, therefore, and -exhorted them man by man not to lose heart. - -“‘My friends,’ said I, ‘this is not the first time that we have been in -danger, and we are in nothing like so bad a case as when the Cyclops -shut us up in his cave; nevertheless, my courage and wise counsel saved -us then, and we shall live to look back on all this as well. Now, -therefore, let us all do as I say, trust in Jove and row on with might -and main. As for you, coxswain, these are your orders; attend to them, -for the ship is in your hands; turn her head away from these steaming -rapids and hug the rock, or she will give you the slip and be over -yonder before you know where you are, and you will be the death of us.’ - -“So they did as I told them; but I said nothing about the awful monster -Scylla, for I knew the men would not go on rowing if I did, but would -huddle together in the hold. In one thing only did I disobey Circe’s -strict instructions—I put on my armour. Then seizing two strong spears -I took my stand on the ship’s bows, for it was there that I expected -first to see the monster of the rock, who was to do my men so much -harm; but I could not make her out anywhere, though I strained my eyes -with looking the gloomy rock all over and over. - -“Then we entered the Straits in great fear of mind, for on the one hand -was Scylla, and on the other dread Charybdis kept sucking up the salt -water. As she vomited it up, it was like the water in a cauldron when -it is boiling over upon a great fire, and the spray reached the top of -the rocks on either side. When she began to suck again, we could see -the water all inside whirling round and round, and it made a deafening -sound as it broke against the rocks. We could see the bottom of the -whirlpool all black with sand and mud, and the men were at their wits -ends for fear. While we were taken up with this, and were expecting -each moment to be our last, Scylla pounced down suddenly upon us and -snatched up my six best men. I was looking at once after both ship and -men, and in a moment I saw their hands and feet ever so high above me, -struggling in the air as Scylla was carrying them off, and I heard them -call out my name in one last despairing cry. As a fisherman, seated, -spear in hand, upon some jutting rock104 throws bait into the water to -deceive the poor little fishes, and spears them with the ox’s horn with -which his spear is shod, throwing them gasping on to the land as he -catches them one by one—even so did Scylla land these panting creatures -on her rock and munch them up at the mouth of her den, while they -screamed and stretched out their hands to me in their mortal agony. -This was the most sickening sight that I saw throughout all my voyages. - -“When we had passed the [Wandering] rocks, with Scylla and terrible -Charybdis, we reached the noble island of the sun-god, where were the -goodly cattle and sheep belonging to the sun Hyperion. While still at -sea in my ship I could bear the cattle lowing as they came home to the -yards, and the sheep bleating. Then I remembered what the blind Theban -prophet Teiresias had told me, and how carefully Aeaean Circe had -warned me to shun the island of the blessed sun-god. So being much -troubled I said to the men, ‘My men, I know you are hard pressed, but -listen while I tell you the prophecy that Teiresias made me, and how -carefully Aeaean Circe warned me to shun the island of the blessed -sun-god, for it was here, she said, that our worst danger would lie. -Head the ship, therefore, away from the island.’ - -“The men were in despair at this, and Eurylochus at once gave me an -insolent answer. ‘Ulysses,’ said he, ‘you are cruel; you are very -strong yourself and never get worn out; you seem to be made of iron, -and now, though your men are exhausted with toil and want of sleep, you -will not let them land and cook themselves a good supper upon this -island, but bid them put out to sea and go faring fruitlessly on -through the watches of the flying night. It is by night that the winds -blow hardest and do so much damage; how can we escape should one of -those sudden squalls spring up from South West or West, which so often -wreck a vessel when our lords the gods are unpropitious? Now, -therefore, let us obey the behests of night and prepare our supper here -hard by the ship; to-morrow morning we will go on board again and put -out to sea.’ - -“Thus spoke Eurylochus, and the men approved his words. I saw that -heaven meant us a mischief and said, ‘You force me to yield, for you -are many against one, but at any rate each one of you must take his -solemn oath that if he meet with a herd of cattle or a large flock of -sheep, he will not be so mad as to kill a single head of either, but -will be satisfied with the food that Circe has given us.’ - -“They all swore as I bade them, and when they had completed their oath -we made the ship fast in a harbour that was near a stream of fresh -water, and the men went ashore and cooked their suppers. As soon as -they had had enough to eat and drink, they began talking about their -poor comrades whom Scylla had snatched up and eaten; this set them -weeping and they went on crying till they fell off into a sound sleep. - -“In the third watch of the night when the stars had shifted their -places, Jove raised a great gale of wind that flew a hurricane so that -land and sea were covered with thick clouds, and night sprang forth out -of the heavens. When the child of morning, rosy-fingered Dawn, -appeared, we brought the ship to land and drew her into a cave wherein -the sea-nymphs hold their courts and dances, and I called the men -together in council. - -“‘My friends,’ said I, ‘we have meat and drink in the ship, let us -mind, therefore, and not touch the cattle, or we shall suffer for it; -for these cattle and sheep belong to the mighty sun, who sees and gives -ear to everything.’ And again they promised that they would obey. - -“For a whole month the wind blew steadily from the South, and there was -no other wind, but only South and East.105 As long as corn and wine -held out the men did not touch the cattle when they were hungry; when, -however, they had eaten all there was in the ship, they were forced to -go further afield, with hook and line, catching birds, and taking -whatever they could lay their hands on; for they were starving. One -day, therefore, I went up inland that I might pray heaven to show me -some means of getting away. When I had gone far enough to be clear of -all my men, and had found a place that was well sheltered from the -wind, I washed my hands and prayed to all the gods in Olympus till by -and by they sent me off into a sweet sleep. - -“Meanwhile Eurylochus had been giving evil counsel to the men, ‘Listen -to me,’ said he, ‘my poor comrades. All deaths are bad enough but there -is none so bad as famine. Why should not we drive in the best of these -cows and offer them in sacrifice to the immortal gods? If we ever get -back to Ithaca, we can build a fine temple to the sun-god and enrich it -with every kind of ornament; if, however, he is determined to sink our -ship out of revenge for these horned cattle, and the other gods are of -the same mind, I for one would rather drink salt water once for all and -have done with it, than be starved to death by inches in such a desert -island as this is.’ - -“Thus spoke Eurylochus, and the men approved his words. Now the cattle, -so fair and goodly, were feeding not far from the ship; the men, -therefore, drove in the best of them, and they all stood round them -saying their prayers, and using young oak-shoots instead of -barley-meal, for there was no barley left. When they had done praying -they killed the cows and dressed their carcasses; they cut out the -thigh bones, wrapped them round in two layers of fat, and set some -pieces of raw meat on top of them. They had no wine with which to make -drink-offerings over the sacrifice while it was cooking, so they kept -pouring on a little water from time to time while the inward meats were -being grilled; then, when the thigh bones were burned and they had -tasted the inward meats, they cut the rest up small and put the pieces -upon the spits. - -“By this time my deep sleep had left me, and I turned back to the ship -and to the sea shore. As I drew near I began to smell hot roast meat, -so I groaned out a prayer to the immortal gods. ‘Father Jove,’ I -exclaimed, ‘and all you other gods who live in everlasting bliss, you -have done me a cruel mischief by the sleep into which you have sent me; -see what fine work these men of mine have been making in my absence.’ - -“Meanwhile Lampetie went straight off to the sun and told him we had -been killing his cows, whereon he flew into a great rage, and said to -the immortals, ‘Father Jove, and all you other gods who live in -everlasting bliss, I must have vengeance on the crew of Ulysses’ ship: -they have had the insolence to kill my cows, which were the one thing I -loved to look upon, whether I was going up heaven or down again. If -they do not square accounts with me about my cows, I will go down to -Hades and shine there among the dead.’ - -“‘Sun,’ said Jove, ‘go on shining upon us gods and upon mankind over -the fruitful earth. I will shiver their ship into little pieces with a -bolt of white lightning as soon as they get out to sea.’ - -“I was told all this by Calypso, who said she had heard it from the -mouth of Mercury. - -“As soon as I got down to my ship and to the sea shore I rebuked each -one of the men separately, but we could see no way out of it, for the -cows were dead already. And indeed the gods began at once to show signs -and wonders among us, for the hides of the cattle crawled about, and -the joints upon the spits began to low like cows, and the meat, whether -cooked or raw, kept on making a noise just as cows do. - -“For six days my men kept driving in the best cows and feasting upon -them, but when Jove the son of Saturn had added a seventh day, the fury -of the gale abated; we therefore went on board, raised our masts, -spread sail, and put out to sea. As soon as we were well away from the -island, and could see nothing but sky and sea, the son of Saturn raised -a black cloud over our ship, and the sea grew dark beneath it. We did -not get on much further, for in another moment we were caught by a -terrific squall from the West that snapped the forestays of the mast so -that it fell aft, while all the ship’s gear tumbled about at the bottom -of the vessel. The mast fell upon the head of the helmsman in the -ship’s stern, so that the bones of his head were crushed to pieces, and -he fell overboard as though he were diving, with no more life left in -him. - -“Then Jove let fly with his thunderbolts, and the ship went round and -round, and was filled with fire and brimstone as the lightning struck -it. The men all fell into the sea; they were carried about in the water -round the ship, looking like so many sea-gulls, but the god presently -deprived them of all chance of getting home again. - -“I stuck to the ship till the sea knocked her sides from her keel -(which drifted about by itself) and struck the mast out of her in the -direction of the keel; but there was a backstay of stout ox-thong still -hanging about it, and with this I lashed the mast and keel together, -and getting astride of them was carried wherever the winds chose to -take me. - -“[The gale from the West had now spent its force, and the wind got into -the South again, which frightened me lest I should be taken back to the -terrible whirlpool of Charybdis. This indeed was what actually -happened, for I was borne along by the waves all night, and by sunrise -had reached the rock of Scylla, and the whirlpool. She was then sucking -down the salt sea water,106 but I was carried aloft toward the fig -tree, which I caught hold of and clung on to like a bat. I could not -plant my feet anywhere so as to stand securely, for the roots were a -long way off and the boughs that overshadowed the whole pool were too -high, too vast, and too far apart for me to reach them; so I hung -patiently on, waiting till the pool should discharge my mast and raft -again—and a very long while it seemed. A jury-man is not more glad to -get home to supper, after having been long detained in court by -troublesome cases, than I was to see my raft beginning to work its way -out of the whirlpool again. At last I let go with my hands and feet, -and fell heavily into the sea, hard by my raft on to which I then got, -and began to row with my hands. As for Scylla, the father of gods and -men would not let her get further sight of me—otherwise I should have -certainly been lost.107 - -“Hence I was carried along for nine days till on the tenth night the -gods stranded me on the Ogygian island, where dwells the great and -powerful goddess Calypso. She took me in and was kind to me, but I need -say no more about this, for I told you and your noble wife all about it -yesterday, and I hate saying the same thing over and over again.” - - - - -BOOK XIII - - -ULYSSES LEAVES SCHERIA AND RETURNS TO ITHACA. - - -Thus did he speak, and they all held their peace throughout the covered -cloister, enthralled by the charm of his story, till presently Alcinous -began to speak. - -“Ulysses,” said he, “now that you have reached my house I doubt not you -will get home without further misadventure no matter how much you have -suffered in the past. To you others, however, who come here night after -night to drink my choicest wine and listen to my bard, I would insist -as follows. Our guest has already packed up the clothes, wrought -gold,108 and other valuables which you have brought for his acceptance; -let us now, therefore, present him further, each one of us, with a -large tripod and a cauldron. We will recoup ourselves by the levy of a -general rate; for private individuals cannot be expected to bear the -burden of such a handsome present.” - -Every one approved of this, and then they went home to bed each in his -own abode. When the child of morning, rosy-fingered Dawn, appeared they -hurried down to the ship and brought their cauldrons with them. -Alcinous went on board and saw everything so securely stowed under the -ship’s benches that nothing could break adrift and injure the rowers. -Then they went to the house of Alcinous to get dinner, and he -sacrificed a bull for them in honour of Jove who is the lord of all. -They set the steaks to grill and made an excellent dinner, after which -the inspired bard, Demodocus, who was a favourite with every one, sang -to them; but Ulysses kept on turning his eyes towards the sun, as -though to hasten his setting, for he was longing to be on his way. As -one who has been all day ploughing a fallow field with a couple of oxen -keeps thinking about his supper and is glad when night comes that he -may go and get it, for it is all his legs can do to carry him, even so -did Ulysses rejoice when the sun went down, and he at once said to the -Phaeacians, addressing himself more particularly to King Alcinous: - -“Sir, and all of you, farewell. Make your drink-offerings and send me -on my way rejoicing, for you have fulfilled my heart’s desire by giving -me an escort, and making me presents, which heaven grant that I may -turn to good account; may I find my admirable wife living in peace -among friends,109 and may you whom I leave behind me give satisfaction -to your wives and children;110 may heaven vouchsafe you every good -grace, and may no evil thing come among your people.” - -Thus did he speak. His hearers all of them approved his saying and -agreed that he should have his escort inasmuch as he had spoken -reasonably. Alcinous therefore said to his servant, “Pontonous, mix -some wine and hand it round to everybody, that we may offer a prayer to -father Jove, and speed our guest upon his way.” - -Pontonous mixed the wine and handed it to every one in turn; the others -each from his own seat made a drink-offering to the blessed gods that -live in heaven, but Ulysses rose and placed the double cup in the hands -of queen Arete. - -“Farewell, queen,” said he, “henceforward and for ever, till age and -death, the common lot of mankind, lay their hands upon you. I now take -my leave; be happy in this house with your children, your people, and -with king Alcinous.” - -As he spoke he crossed the threshold, and Alcinous sent a man to -conduct him to his ship and to the sea shore. Arete also sent some -maidservants with him—one with a clean shirt and cloak, another to -carry his strong box, and a third with corn and wine. When they got to -the water side the crew took these things and put them on board, with -all the meat and drink; but for Ulysses they spread a rug and a linen -sheet on deck that he might sleep soundly in the stern of the ship. -Then he too went on board and lay down without a word, but the crew -took every man his place and loosed the hawser from the pierced stone -to which it had been bound. Thereon, when they began rowing out to sea, -Ulysses fell into a deep, sweet, and almost deathlike slumber.111 - -The ship bounded forward on her way as a four in hand chariot flies -over the course when the horses feel the whip. Her prow curvetted as it -were the neck of a stallion, and a great wave of dark blue water -seethed in her wake. She held steadily on her course, and even a -falcon, swiftest of all birds, could not have kept pace with her. Thus, -then, she cut her way through the water, carrying one who was as -cunning as the gods, but who was now sleeping peacefully, forgetful of -all that he had suffered both on the field of battle and by the waves -of the weary sea. - -When the bright star that heralds the approach of dawn began to show, -the ship drew near to land.112 Now there is in Ithaca a haven of the -old merman Phorcys, which lies between two points that break the line -of the sea and shut the harbour in. These shelter it from the storms of -wind and sea that rage outside, so that, when once within it, a ship -may lie without being even moored. At the head of this harbour there is -a large olive tree, and at no great distance a fine overarching cavern -sacred to the nymphs who are called Naiads.113 There are mixing bowls -within it and wine-jars of stone, and the bees hive there. Moreover, -there are great looms of stone on which the nymphs weave their robes of -sea purple—very curious to see—and at all times there is water within -it. It has two entrances, one facing North by which mortals can go down -into the cave, while the other comes from the South and is more -mysterious; mortals cannot possibly get in by it, it is the way taken -by the gods. - -Into this harbour, then, they took their ship, for they knew the -place.114 She had so much way upon her that she ran half her own length -on to the shore;115 when, however, they had landed, the first thing -they did was to lift Ulysses with his rug and linen sheet out of the -ship, and lay him down upon the sand still fast asleep. Then they took -out the presents which Minerva had persuaded the Phaeacians to give him -when he was setting out on his voyage homewards. They put these all -together by the root of the olive tree, away from the road, for fear -some passer by116 might come and steal them before Ulysses awoke; and -then they made the best of their way home again. - -But Neptune did not forget the threats with which he had already -threatened Ulysses, so he took counsel with Jove. “Father Jove,” said -he, “I shall no longer be held in any sort of respect among you gods, -if mortals like the Phaeacians, who are my own flesh and blood, show -such small regard for me. I said I would let Ulysses get home when he -had suffered sufficiently. I did not say that he should never get home -at all, for I knew you had already nodded your head about it, and -promised that he should do so; but now they have brought him in a ship -fast asleep and have landed him in Ithaca after loading him with more -magnificent presents of bronze, gold, and raiment than he would ever -have brought back from Troy, if he had had his share of the spoil and -got home without misadventure.” - -And Jove answered, “What, O Lord of the Earthquake, are you talking -about? The gods are by no means wanting in respect for you. It would be -monstrous were they to insult one so old and honoured as you are. As -regards mortals, however, if any of them is indulging in insolence and -treating you disrespectfully, it will always rest with yourself to deal -with him as you may think proper, so do just as you please.” - -“I should have done so at once,” replied Neptune, “if I were not -anxious to avoid anything that might displease you; now, therefore, I -should like to wreck the Phaeacian ship as it is returning from its -escort. This will stop them from escorting people in future; and I -should also like to bury their city under a huge mountain.” - -“My good friend,” answered Jove, “I should recommend you at the very -moment when the people from the city are watching the ship on her way, -to turn it into a rock near the land and looking like a ship. This will -astonish everybody, and you can then bury their city under the -mountain.” - -When earth-encircling Neptune heard this he went to Scheria where the -Phaeacians live, and stayed there till the ship, which was making rapid -way, had got close in. Then he went up to it, turned it into stone, and -drove it down with the flat of his hand so as to root it in the ground. -After this he went away. - -The Phaeacians then began talking among themselves, and one would turn -towards his neighbour, saying, “Bless my heart, who is it that can have -rooted the ship in the sea just as she was getting into port? We could -see the whole of her only a moment ago.” - -This was how they talked, but they knew nothing about it; and Alcinous -said, “I remember now the old prophecy of my father. He said that -Neptune would be angry with us for taking every one so safely over the -sea, and would one day wreck a Phaeacian ship as it was returning from -an escort, and bury our city under a high mountain. This was what my -old father used to say, and now it is all coming true.117 Now therefore -let us all do as I say; in the first place we must leave off giving -people escorts when they come here, and in the next let us sacrifice -twelve picked bulls to Neptune that he may have mercy upon us, and not -bury our city under the high mountain.” When the people heard this they -were afraid and got ready the bulls. - -Thus did the chiefs and rulers of the Phaeacians pray to king Neptune, -standing round his altar; and at the same time118 Ulysses woke up once -more upon his own soil. He had been so long away that he did not know -it again; moreover, Jove’s daughter Minerva had made it a foggy day, so -that people might not know of his having come, and that she might tell -him everything without either his wife or his fellow citizens and -friends recognising him119 until he had taken his revenge upon the -wicked suitors. Everything, therefore, seemed quite different to -him—the long straight tracks, the harbours, the precipices, and the -goodly trees, appeared all changed as he started up and looked upon his -native land. So he smote his thighs with the flat of his hands and -cried aloud despairingly. - -“Alas,” he exclaimed, “among what manner of people am I fallen? Are -they savage and uncivilised or hospitable and humane? Where shall I put -all this treasure, and which way shall I go? I wish I had staid over -there with the Phaeacians; or I could have gone to some other great -chief who would have been good to me and given me an escort. As it is I -do not know where to put my treasure, and I cannot leave it here for -fear somebody else should get hold of it. In good truth the chiefs and -rulers of the Phaeacians have not been dealing fairly by me, and have -left me in the wrong country; they said they would take me back to -Ithaca and they have not done so: may Jove the protector of suppliants -chastise them, for he watches over everybody and punishes those who do -wrong. Still, I suppose I must count my goods and see if the crew have -gone off with any of them.” - -He counted his goodly coppers and cauldrons, his gold and all his -clothes, but there was nothing missing; still he kept grieving about -not being in his own country, and wandered up and down by the shore of -the sounding sea bewailing his hard fate. Then Minerva came up to him -disguised as a young shepherd of delicate and princely mien, with a -good cloak folded double about her shoulders; she had sandals on her -comely feet and held a javelin in her hand. Ulysses was glad when he -saw her, and went straight up to her. - -“My friend,” said he, “you are the first person whom I have met with in -this country; I salute you, therefore, and beg you to be well disposed -towards me. Protect these my goods, and myself too, for I embrace your -knees and pray to you as though you were a god. Tell me, then, and tell -me truly, what land and country is this? Who are its inhabitants? Am I -on an island, or is this the sea board of some continent?” - -Minerva answered, “Stranger, you must be very simple, or must have come -from somewhere a long way off, not to know what country this is. It is -a very celebrated place, and everybody knows it East and West. It is -rugged and not a good driving country, but it is by no means a bad -island for what there is of it. It grows any quantity of corn and also -wine, for it is watered both by rain and dew; it breeds cattle also and -goats; all kinds of timber grow here, and there are watering places -where the water never runs dry; so, sir, the name of Ithaca is known -even as far as Troy, which I understand to be a long way off from this -Achaean country.” - -Ulysses was glad at finding himself, as Minerva told him, in his own -country, and he began to answer, but he did not speak the truth, and -made up a lying story in the instinctive wiliness of his heart. - -“I heard of Ithaca,” said he, “when I was in Crete beyond the seas, and -now it seems I have reached it with all these treasures. I have left as -much more behind me for my children, but am flying because I killed -Orsilochus son of Idomeneus, the fleetest runner in Crete. I killed him -because he wanted to rob me of the spoils I had got from Troy with so -much trouble and danger both on the field of battle and by the waves of -the weary sea; he said I had not served his father loyally at Troy as -vassal, but had set myself up as an independent ruler, so I lay in wait -for him with one of my followers by the road side, and speared him as -he was coming into town from the country. It was a very dark night and -nobody saw us; it was not known, therefore, that I had killed him, but -as soon as I had done so I went to a ship and besought the owners, who -were Phoenicians, to take me on board and set me in Pylos or in Elis -where the Epeans rule, giving them as much spoil as satisfied them. -They meant no guile, but the wind drove them off their course, and we -sailed on till we came hither by night. It was all we could do to get -inside the harbour, and none of us said a word about supper though we -wanted it badly, but we all went on shore and lay down just as we were. -I was very tired and fell asleep directly, so they took my goods out of -the ship, and placed them beside me where I was lying upon the sand. -Then they sailed away to Sidonia, and I was left here in great distress -of mind.” - -Such was his story, but Minerva smiled and caressed him with her hand. -Then she took the form of a woman, fair, stately, and wise, “He must be -indeed a shifty lying fellow,” said she, “who could surpass you in all -manner of craft even though you had a god for your antagonist. Dare -devil that you are, full of guile, unwearying in deceit, can you not -drop your tricks and your instinctive falsehood, even now that you are -in your own country again? We will say no more, however, about this, -for we can both of us deceive upon occasion—you are the most -accomplished counsellor and orator among all mankind, while I for -diplomacy and subtlety have no equal among the gods. Did you not know -Jove’s daughter Minerva—me, who have been ever with you, who kept watch -over you in all your troubles, and who made the Phaeacians take so -great a liking to you? And now, again, I am come here to talk things -over with you, and help you to hide the treasure I made the Phaeacians -give you; I want to tell you about the troubles that await you in your -own house; you have got to face them, but tell no one, neither man nor -woman, that you have come home again. Bear everything, and put up with -every man’s insolence, without a word.” - -And Ulysses answered, “A man, goddess, may know a great deal, but you -are so constantly changing your appearance that when he meets you it is -a hard matter for him to know whether it is you or not. This much, -however, I know exceedingly well; you were very kind to me as long as -we Achaeans were fighting before Troy, but from the day on which we -went on board ship after having sacked the city of Priam, and heaven -dispersed us—from that day, Minerva, I saw no more of you, and cannot -ever remember your coming to my ship to help me in a difficulty; I had -to wander on sick and sorry till the gods delivered me from evil and I -reached the city of the Phaeacians, where you encouraged me and took me -into the town.120 And now, I beseech you in your father’s name, tell me -the truth, for I do not believe I am really back in Ithaca. I am in -some other country and you are mocking me and deceiving me in all you -have been saying. Tell me then truly, have I really got back to my own -country?” - -“You are always taking something of that sort in your head,” replied -Minerva, “and that is why I cannot desert you in your afflictions; you -are so plausible, shrewd and shifty. Any one but yourself on returning -from so long a voyage would at once have gone home to see his wife and -children, but you do not seem to care about asking after them or -hearing any news about them till you have exploited your wife, who -remains at home vainly grieving for you, and having no peace night or -day for the tears she sheds on your behalf. As for my not coming near -you, I was never uneasy about you, for I was certain you would get back -safely though you would lose all your men, and I did not wish to -quarrel with my uncle Neptune, who never forgave you for having blinded -his son.121 I will now, however, point out to you the lie of the land, -and you will then perhaps believe me. This is the haven of the old -merman Phorcys, and here is the olive tree that grows at the head of -it; [near it is the cave sacred to the Naiads;122 here too is the -overarching cavern in which you have offered many an acceptable -hecatomb to the nymphs, and this is the wooded mountain Neritum.” - -As she spoke the goddess dispersed the mist and the land appeared. Then -Ulysses rejoiced at finding himself again in his own land, and kissed -the bounteous soil; he lifted up his hands and prayed to the nymphs, -saying, “Naiad nymphs, daughters of Jove, I made sure that I was never -again to see you, now therefore I greet you with all loving -salutations, and I will bring you offerings as in the old days, if -Jove’s redoubtable daughter will grant me life, and bring my son to -manhood.” - -“Take heart, and do not trouble yourself about that,” rejoined Minerva, -“let us rather set about stowing your things at once in the cave, where -they will be quite safe. Let us see how we can best manage it all.” - -Therewith she went down into the cave to look for the safest hiding -places, while Ulysses brought up all the treasure of gold, bronze, and -good clothing which the Phaeacians had given him. They stowed -everything carefully away, and Minerva set a stone against the door of -the cave. Then the two sat down by the root of the great olive, and -consulted how to compass the destruction of the wicked suitors. - -“Ulysses,” said Minerva, “noble son of Laertes, think how you can lay -hands on these disreputable people who have been lording it in your -house these three years, courting your wife and making wedding presents -to her, while she does nothing but lament your absence, giving hope and -sending encouraging messages123 to every one of them, but meaning the -very opposite of all she says.” - -And Ulysses answered, “In good truth, goddess, it seems I should have -come to much the same bad end in my own house as Agamemnon did, if you -had not given me such timely information. Advise me how I shall best -avenge myself. Stand by my side and put your courage into my heart as -on the day when we loosed Troy’s fair diadem from her brow. Help me now -as you did then, and I will fight three hundred men, if you, goddess, -will be with me.” - -“Trust me for that,” said she, “I will not lose sight of you when once -we set about it, and I imagine that some of those who are devouring -your substance will then bespatter the pavement with their blood and -brains. I will begin by disguising you so that no human being shall -know you; I will cover your body with wrinkles; you shall lose all your -yellow hair; I will clothe you in a garment that shall fill all who see -it with loathing; I will blear your fine eyes for you, and make you an -unseemly object in the sight of the suitors, of your wife, and of the -son whom you left behind you. Then go at once to the swineherd who is -in charge of your pigs; he has been always well affected towards you, -and is devoted to Penelope and your son; you will find him feeding his -pigs near the rock that is called Raven124 by the fountain Arethusa, -where they are fattening on beechmast and spring water after their -manner. Stay with him and find out how things are going, while I -proceed to Sparta and see your son, who is with Menelaus at Lacedaemon, -where he has gone to try and find out whether you are still alive.”125 - -“But why,” said Ulysses, “did you not tell him, for you knew all about -it? Did you want him too to go sailing about amid all kinds of hardship -while others are eating up his estate?” - -Minerva answered, “Never mind about him, I sent him that he might be -well spoken of for having gone. He is in no sort of difficulty, but is -staying quite comfortably with Menelaus, and is surrounded with -abundance of every kind. The suitors have put out to sea and are lying -in wait for him, for they mean to kill him before he can get home. I do -not much think they will succeed, but rather that some of those who are -now eating up your estate will first find a grave themselves.” - -As she spoke Minerva touched him with her wand and covered him with -wrinkles, took away all his yellow hair, and withered the flesh over -his whole body; she bleared his eyes, which were naturally very fine -ones; she changed his clothes and threw an old rag of a wrap about him, -and a tunic, tattered, filthy, and begrimed with smoke; she also gave -him an undressed deer skin as an outer garment, and furnished him with -a staff and a wallet all in holes, with a twisted thong for him to -sling it over his shoulder. - -When the pair had thus laid their plans they parted, and the goddess -went straight to Lacedaemon to fetch Telemachus. - - - - -BOOK XIV - - -ULYSSES IN THE HUT WITH EUMAEUS. - - -Ulysses now left the haven, and took the rough track up through the -wooded country and over the crest of the mountain till he reached the -place where Minerva had said that he would find the swineherd, who was -the most thrifty servant he had. He found him sitting in front of his -hut, which was by the yards that he had built on a site which could be -seen from far. He had made them spacious126 and fair to see, with a -free run for the pigs all round them; he had built them during his -master’s absence, of stones which he had gathered out of the ground, -without saying anything to Penelope or Laertes, and he had fenced them -on top with thorn bushes. Outside the yard he had run a strong fence of -oaken posts, split, and set pretty close together, while inside he had -built twelve styes near one another for the sows to lie in. There were -fifty pigs wallowing in each stye, all of them breeding sows; but the -boars slept outside and were much fewer in number, for the suitors kept -on eating them, and the swineherd had to send them the best he had -continually. There were three hundred and sixty boar pigs, and the -herdsman’s four hounds, which were as fierce as wolves, slept always -with them. The swineherd was at that moment cutting out a pair of -sandals127 from a good stout ox hide. Three of his men were out herding -the pigs in one place or another, and he had sent the fourth to town -with a boar that he had been forced to send the suitors that they might -sacrifice it and have their fill of meat. - -When the hounds saw Ulysses they set up a furious barking and flew at -him, but Ulysses was cunning enough to sit down and loose his hold of -the stick that he had in his hand: still, he would have been torn by -them in his own homestead had not the swineherd dropped his ox hide, -rushed full speed through the gate of the yard and driven the dogs off -by shouting and throwing stones at them. Then he said to Ulysses, “Old -man, the dogs were likely to have made short work of you, and then you -would have got me into trouble. The gods have given me quite enough -worries without that, for I have lost the best of masters, and am in -continual grief on his account. I have to attend swine for other people -to eat, while he, if he yet lives to see the light of day, is starving -in some distant land. But come inside, and when you have had your fill -of bread and wine, tell me where you come from, and all about your -misfortunes.” - -On this the swineherd led the way into the hut and bade him sit down. -He strewed a good thick bed of rushes upon the floor, and on the top of -this he threw the shaggy chamois skin—a great thick one—on which he -used to sleep by night. Ulysses was pleased at being made thus welcome, -and said “May Jove, sir, and the rest of the gods grant you your -heart’s desire in return for the kind way in which you have received -me.” - -To this you answered, O swineherd Eumaeus, “Stranger, though a still -poorer man should come here, it would not be right for me to insult -him, for all strangers and beggars are from Jove. You must take what -you can get and be thankful, for servants live in fear when they have -young lords for their masters; and this is my misfortune now, for -heaven has hindered the return of him who would have been always good -to me and given me something of my own—a house, a piece of land, a good -looking wife, and all else that a liberal master allows a servant who -has worked hard for him, and whose labour the gods have prospered as -they have mine in the situation which I hold. If my master had grown -old here he would have done great things by me, but he is gone, and I -wish that Helen’s whole race were utterly destroyed, for she has been -the death of many a good man. It was this matter that took my master to -Ilius, the land of noble steeds, to fight the Trojans in the cause of -king Agamemnon.” - -As he spoke he bound his girdle round him and went to the styes where -the young sucking pigs were penned. He picked out two which he brought -back with him and sacrificed. He singed them, cut them up, and spitted -them; when the meat was cooked he brought it all in and set it before -Ulysses, hot and still on the spit, whereon Ulysses sprinkled it over -with white barley meal. The swineherd then mixed wine in a bowl of -ivy-wood, and taking a seat opposite Ulysses told him to begin. - -“Fall to, stranger,” said he, “on a dish of servant’s pork. The fat -pigs have to go to the suitors, who eat them up without shame or -scruple; but the blessed gods love not such shameful doings, and -respect those who do what is lawful and right. Even the fierce -freebooters who go raiding on other people’s land, and Jove gives them -their spoil—even they, when they have filled their ships and got home -again live conscience-stricken, and look fearfully for judgement; but -some god seems to have told these people that Ulysses is dead and gone; -they will not, therefore, go back to their own homes and make their -offers of marriage in the usual way, but waste his estate by force, -without fear or stint. Not a day or night comes out of heaven, but they -sacrifice not one victim nor two only, and they take the run of his -wine, for he was exceedingly rich. No other great man either in Ithaca -or on the mainland is as rich as he was; he had as much as twenty men -put together. I will tell you what he had. There are twelve herds of -cattle upon the main land, and as many flocks of sheep, there are also -twelve droves of pigs, while his own men and hired strangers feed him -twelve widely spreading herds of goats. Here in Ithaca he runs even -large flocks of goats on the far end of the island, and they are in the -charge of excellent goat herds. Each one of these sends the suitors the -best goat in the flock every day. As for myself, I am in charge of the -pigs that you see here, and I have to keep picking out the best I have -and sending it to them.” - -This was his story, but Ulysses went on eating and drinking ravenously -without a word, brooding his revenge. When he had eaten enough and was -satisfied, the swineherd took the bowl from which he usually drank, -filled it with wine, and gave it to Ulysses, who was pleased, and said -as he took it in his hands, “My friend, who was this master of yours -that bought you and paid for you, so rich and so powerful as you tell -me? You say he perished in the cause of King Agamemnon; tell me who he -was, in case I may have met with such a person. Jove and the other gods -know, but I may be able to give you news of him, for I have travelled -much.” - -Eumaeus answered, “Old man, no traveller who comes here with news will -get Ulysses’ wife and son to believe his story. Nevertheless, tramps in -want of a lodging keep coming with their mouths full of lies, and not a -word of truth; every one who finds his way to Ithaca goes to my -mistress and tells her falsehoods, whereon she takes them in, makes -much of them, and asks them all manner of questions, crying all the -time as women will when they have lost their husbands. And you too, old -man, for a shirt and a cloak would doubtless make up a very pretty -story. But the wolves and birds of prey have long since torn Ulysses to -pieces, or the fishes of the sea have eaten him, and his bones are -lying buried deep in sand upon some foreign shore; he is dead and gone, -and a bad business it is for all his friends—for me especially; go -where I may I shall never find so good a master, not even if I were to -go home to my mother and father where I was bred and born. I do not so -much care, however, about my parents now, though I should dearly like -to see them again in my own country; it is the loss of Ulysses that -grieves me most; I cannot speak of him without reverence though he is -here no longer, for he was very fond of me, and took such care of me -that wherever he may be I shall always honour his memory.” - -“My friend,” replied Ulysses, “you are very positive, and very hard of -belief about your master’s coming home again, nevertheless I will not -merely say, but will swear, that he is coming. Do not give me anything -for my news till he has actually come, you may then give me a shirt and -cloak of good wear if you will. I am in great want, but I will not take -anything at all till then, for I hate a man, even as I hate hell fire, -who lets his poverty tempt him into lying. I swear by king Jove, by the -rites of hospitality, and by that hearth of Ulysses to which I have now -come, that all will surely happen as I have said it will. Ulysses will -return in this self same year; with the end of this moon and the -beginning of the next he will be here to do vengeance on all those who -are ill treating his wife and son.” - -To this you answered, O swineherd Eumaeus, “Old man, you will neither -get paid for bringing good news, nor will Ulysses ever come home; drink -your wine in peace, and let us talk about something else. Do not keep -on reminding me of all this; it always pains me when any one speaks -about my honoured master. As for your oath we will let it alone, but I -only wish he may come, as do Penelope, his old father Laertes, and his -son Telemachus. I am terribly unhappy too about this same boy of his; -he was running up fast into manhood, and bade fare to be no worse man, -face and figure, than his father, but some one, either god or man, has -been unsettling his mind, so he has gone off to Pylos to try and get -news of his father, and the suitors are lying in wait for him as he is -coming home, in the hope of leaving the house of Arceisius without a -name in Ithaca. But let us say no more about him, and leave him to be -taken, or else to escape if the son of Saturn holds his hand over him -to protect him. And now, old man, tell me your own story; tell me also, -for I want to know, who you are and where you come from. Tell me of -your town and parents, what manner of ship you came in, how crew -brought you to Ithaca, and from what country they professed to come—for -you cannot have come by land.” - -And Ulysses answered, “I will tell you all about it. If there were meat -and wine enough, and we could stay here in the hut with nothing to do -but to eat and drink while the others go to their work, I could easily -talk on for a whole twelve months without ever finishing the story of -the sorrows with which it has pleased heaven to visit me. - -“I am by birth a Cretan; my father was a well to do man, who had many -sons born in marriage, whereas I was the son of a slave whom he had -purchased for a concubine; nevertheless, my father Castor son of Hylax -(whose lineage I claim, and who was held in the highest honour among -the Cretans for his wealth, prosperity, and the valour of his sons) put -me on the same level with my brothers who had been born in wedlock. -When, however, death took him to the house of Hades, his sons divided -his estate and cast lots for their shares, but to me they gave a -holding and little else; nevertheless, my valour enabled me to marry -into a rich family, for I was not given to bragging, or shirking on the -field of battle. It is all over now; still, if you look at the straw -you can see what the ear was, for I have had trouble enough and to -spare. Mars and Minerva made me doughty in war; when I had picked my -men to surprise the enemy with an ambuscade I never gave death so much -as a thought, but was the first to leap forward and spear all whom I -could overtake. Such was I in battle, but I did not care about farm -work, nor the frugal home life of those who would bring up children. My -delight was in ships, fighting, javelins, and arrows—things that most -men shudder to think of; but one man likes one thing and another -another, and this was what I was most naturally inclined to. Before the -Achaeans went to Troy, nine times was I in command of men and ships on -foreign service, and I amassed much wealth. I had my pick of the spoil -in the first instance, and much more was allotted to me later on. - -“My house grew apace and I became a great man among the Cretans, but -when Jove counselled that terrible expedition, in which so many -perished, the people required me and Idomeneus to lead their ships to -Troy, and there was no way out of it, for they insisted on our doing -so. There we fought for nine whole years, but in the tenth we sacked -the city of Priam and sailed home again as heaven dispersed us. Then it -was that Jove devised evil against me. I spent but one month happily -with my children, wife, and property, and then I conceived the idea of -making a descent on Egypt, so I fitted out a fine fleet and manned it. -I had nine ships, and the people flocked to fill them. For six days I -and my men made feast, and I found them many victims both for sacrifice -to the gods and for themselves, but on the seventh day we went on board -and set sail from Crete with a fair North wind behind us though we were -going down a river. Nothing went ill with any of our ships, and we had -no sickness on board, but sat where we were and let the ships go as the -wind and steersmen took them. On the fifth day we reached the river -Aegyptus; there I stationed my ships in the river, bidding my men stay -by them and keep guard over them while I sent out scouts to reconnoitre -from every point of vantage. - -“But the men disobeyed my orders, took to their own devices, and -ravaged the land of the Egyptians, killing the men, and taking their -wives and children captive. The alarm was soon carried to the city, and -when they heard the war cry, the people came out at daybreak till the -plain was filled with horsemen and foot soldiers and with the gleam of -armour. Then Jove spread panic among my men, and they would no longer -face the enemy, for they found themselves surrounded. The Egyptians -killed many of us, and took the rest alive to do forced labour for -them. Jove, however, put it in my mind to do thus—and I wish I had died -then and there in Egypt instead, for there was much sorrow in store for -me—I took off my helmet and shield and dropped my spear from my hand; -then I went straight up to the king’s chariot, clasped his knees and -kissed them, whereon he spared my life, bade me get into his chariot, -and took me weeping to his own home. Many made at me with their ashen -spears and tried to kill me in their fury, but the king protected me, -for he feared the wrath of Jove the protector of strangers, who -punishes those who do evil. - -“I stayed there for seven years and got together much money among the -Egyptians, for they all gave me something; but when it was now going on -for eight years there came a certain Phoenician, a cunning rascal, who -had already committed all sorts of villainy, and this man talked me -over into going with him to Phoenicia, where his house and his -possessions lay. I stayed there for a whole twelve months, but at the -end of that time when months and days had gone by till the same season -had come round again, he set me on board a ship bound for Libya, on a -pretence that I was to take a cargo along with him to that place, but -really that he might sell me as a slave and take the money I fetched. I -suspected his intention, but went on board with him, for I could not -help it. - -“The ship ran before a fresh North wind till we had reached the sea -that lies between Crete and Libya; there, however, Jove counselled -their destruction, for as soon as we were well out from Crete and could -see nothing but sea and sky, he raised a black cloud over our ship and -the sea grew dark beneath it. Then Jove let fly with his thunderbolts -and the ship went round and round and was filled with fire and -brimstone as the lightning struck it. The men fell all into the sea; -they were carried about in the water round the ship looking like so -many sea-gulls, but the god presently deprived them of all chance of -getting home again. I was all dismayed. Jove, however, sent the ship’s -mast within my reach, which saved my life, for I clung to it, and -drifted before the fury of the gale. Nine days did I drift but in the -darkness of the tenth night a great wave bore me on to the Thesprotian -coast. There Pheidon king of the Thesprotians entertained me hospitably -without charging me anything at all—for his son found me when I was -nearly dead with cold and fatigue, whereon he raised me by the hand, -took me to his father’s house and gave me clothes to wear. - -“There it was that I heard news of Ulysses, for the king told me he had -entertained him, and shown him much hospitality while he was on his -homeward journey. He showed me also the treasure of gold, and wrought -iron that Ulysses had got together. There was enough to keep his family -for ten generations, so much had he left in the house of king Pheidon. -But the king said Ulysses had gone to Dodona that he might learn Jove’s -mind from the god’s high oak tree, and know whether after so long an -absence he should return to Ithaca openly, or in secret. Moreover the -king swore in my presence, making drink-offerings in his own house as -he did so, that the ship was by the water side, and the crew found, -that should take him to his own country. He sent me off however before -Ulysses returned, for there happened to be a Thesprotian ship sailing -for the wheat-growing island of Dulichium, and he told those in charge -of her to be sure and take me safely to King Acastus. - -“These men hatched a plot against me that would have reduced me to the -very extreme of misery, for when the ship had got some way out from -land they resolved on selling me as a slave. They stripped me of the -shirt and cloak that I was wearing, and gave me instead the tattered -old clouts in which you now see me; then, towards nightfall, they -reached the tilled lands of Ithaca, and there they bound me with a -strong rope fast in the ship, while they went on shore to get supper by -the sea side. But the gods soon undid my bonds for me, and having drawn -my rags over my head I slid down the rudder into the sea, where I -struck out and swam till I was well clear of them, and came ashore near -a thick wood in which I lay concealed. They were very angry at my -having escaped and went searching about for me, till at last they -thought it was no further use and went back to their ship. The gods, -having hidden me thus easily, then took me to a good man’s door—for it -seems that I am not to die yet awhile.” - -To this you answered, O swineherd Eumaeus, “Poor unhappy stranger, I -have found the story of your misfortunes extremely interesting, but -that part about Ulysses is not right; and you will never get me to -believe it. Why should a man like you go about telling lies in this -way? I know all about the return of my master. The gods one and all of -them detest him, or they would have taken him before Troy, or let him -die with friends around him when the days of his fighting were done; -for then the Achaeans would have built a mound over his ashes and his -son would have been heir to his renown, but now the storm winds have -spirited him away we know not whither. - -“As for me I live out of the way here with the pigs, and never go to -the town unless when Penelope sends for me on the arrival of some news -about Ulysses. Then they all sit round and ask questions, both those -who grieve over the king’s absence, and those who rejoice at it because -they can eat up his property without paying for it. For my own part I -have never cared about asking anyone else since the time when I was -taken in by an Aetolian, who had killed a man and come a long way till -at last he reached my station, and I was very kind to him. He said he -had seen Ulysses with Idomeneus among the Cretans, refitting his ships -which had been damaged in a gale. He said Ulysses would return in the -following summer or autumn with his men, and that he would bring back -much wealth. And now you, you unfortunate old man, since fate has -brought you to my door, do not try to flatter me in this way with vain -hopes. It is not for any such reason that I shall treat you kindly, but -only out of respect for Jove the god of hospitality, as fearing him and -pitying you.” - -Ulysses answered, “I see that you are of an unbelieving mind; I have -given you my oath, and yet you will not credit me; let us then make a -bargain, and call all the gods in heaven to witness it. If your master -comes home, give me a cloak and shirt of good wear, and send me to -Dulichium where I want to go; but if he does not come as I say he will, -set your men on to me, and tell them to throw me from yonder precipice, -as a warning to tramps not to go about the country telling lies.” - -“And a pretty figure I should cut then,” replied Eumaeus, “both now and -hereafter, if I were to kill you after receiving you into my hut and -showing you hospitality. I should have to say my prayers in good -earnest if I did; but it is just supper time and I hope my men will -come in directly, that we may cook something savoury for supper.” - -Thus did they converse, and presently the swineherds came up with the -pigs, which were then shut up for the night in their styes, and a -tremendous squealing they made as they were being driven into them. But -Eumaeus called to his men and said, “Bring in the best pig you have, -that I may sacrifice him for this stranger, and we will take toll of -him ourselves. We have had trouble enough this long time feeding pigs, -while others reap the fruit of our labour.” - -On this he began chopping firewood, while the others brought in a fine -fat five year old boar pig, and set it at the altar. Eumaeus did not -forget the gods, for he was a man of good principles, so the first -thing he did was to cut bristles from the pig’s face and throw them -into the fire, praying to all the gods as he did so that Ulysses might -return home again. Then he clubbed the pig with a billet of oak which -he had kept back when he was chopping the firewood, and stunned it, -while the others slaughtered and singed it. Then they cut it up, and -Eumaeus began by putting raw pieces from each joint on to some of the -fat; these he sprinkled with barley meal, and laid upon the embers; -they cut the rest of the meat up small, put the pieces upon the spits -and roasted them till they were done; when they had taken them off the -spits they threw them on to the dresser in a heap. The swineherd, who -was a most equitable man, then stood up to give every one his share. He -made seven portions; one of these he set apart for Mercury the son of -Maia and the nymphs, praying to them as he did so; the others he dealt -out to the men man by man. He gave Ulysses some slices cut lengthways -down the loin as a mark of especial honour, and Ulysses was much -pleased. “I hope, Eumaeus,” said he, “that Jove will be as well -disposed towards you as I am, for the respect you are showing to an -outcast like myself.” - -To this you answered, O swineherd Eumaeus, “Eat, my good fellow, and -enjoy your supper, such as it is. God grants this, and withholds that, -just as he thinks right, for he can do whatever he chooses.” - -As he spoke he cut off the first piece and offered it as a burnt -sacrifice to the immortal gods; then he made them a drink-offering, put -the cup in the hands of Ulysses, and sat down to his own portion. -Mesaulius brought them their bread; the swineherd had brought this man -on his own account from among the Taphians during his master’s absence, -and had paid for him with his own money without saying anything either -to his mistress or Laertes. They then laid their hands upon the good -things that were before them, and when they had had enough to eat and -drink, Mesaulius took away what was left of the bread, and they all -went to bed after having made a hearty supper. - -Now the night came on stormy and very dark, for there was no moon. It -poured without ceasing, and the wind blew strong from the West, which -is a wet quarter, so Ulysses thought he would see whether Eumaeus, in -the excellent care he took of him, would take off his own cloak and -give it him, or make one of his men give him one. “Listen to me,” said -he, “Eumaeus and the rest of you; when I have said a prayer I will tell -you something. It is the wine that makes me talk in this way; wine will -make even a wise man fall to singing; it will make him chuckle and -dance and say many a word that he had better leave unspoken; still, as -I have begun, I will go on. Would that I were still young and strong as -when we got up an ambuscade before Troy. Menelaus and Ulysses were the -leaders, but I was in command also, for the other two would have it so. -When we had come up to the wall of the city we crouched down beneath -our armour and lay there under cover of the reeds and thick brushwood -that grew about the swamp. It came on to freeze with a North wind -blowing; the snow fell small and fine like hoar frost, and our shields -were coated thick with rime. The others had all got cloaks and shirts, -and slept comfortably enough with their shields about their shoulders, -but I had carelessly left my cloak behind me, not thinking that I -should be too cold, and had gone off in nothing but my shirt and -shield. When the night was two-thirds through and the stars had shifted -their places, I nudged Ulysses who was close to me with my elbow, and -he at once gave me his ear. - -“‘Ulysses,’ said I, ‘this cold will be the death of me, for I have no -cloak; some god fooled me into setting off with nothing on but my -shirt, and I do not know what to do.’ - -“Ulysses, who was as crafty as he was valiant, hit upon the following -plan: - -“‘Keep still,’ said he in a low voice, ‘or the others will hear you.’ -Then he raised his head on his elbow. - -“‘My friends,’ said he, ‘I have had a dream from heaven in my sleep. We -are a long way from the ships; I wish some one would go down and tell -Agamemnon to send us up more men at once.’ - -“On this Thoas son of Andraemon threw off his cloak and set out running -to the ships, whereon I took the cloak and lay in it comfortably enough -till morning. Would that I were still young and strong as I was in -those days, for then some one of you swineherds would give me a cloak -both out of good will and for the respect due to a brave soldier; but -now people look down upon me because my clothes are shabby.” - -And Eumaeus answered, “Old man, you have told us an excellent story, -and have said nothing so far but what is quite satisfactory; for the -present, therefore, you shall want neither clothing nor anything else -that a stranger in distress may reasonably expect, but to-morrow -morning you have to shake your own old rags about your body again, for -we have not many spare cloaks nor shirts up here, but every man has -only one. When Ulysses’ son comes home again he will give you both -cloak and shirt, and send you wherever you may want to go.” - -With this he got up and made a bed for Ulysses by throwing some -goatskins and sheepskins on the ground in front of the fire. Here -Ulysses lay down, and Eumaeus covered him over with a great heavy cloak -that he kept for a change in case of extraordinarily bad weather. - -Thus did Ulysses sleep, and the young men slept beside him. But the -swineherd did not like sleeping away from his pigs, so he got ready to -go outside, and Ulysses was glad to see that he looked after his -property during his master’s absence. First he slung his sword over his -brawny shoulders and put on a thick cloak to keep out the wind. He also -took the skin of a large and well fed goat, and a javelin in case of -attack from men or dogs. Thus equipped he went to his rest where the -pigs were camping under an overhanging rock that gave them shelter from -the North wind. - - - - -BOOK XV - - -MINERVA SUMMONS TELEMACHUS FROM LACEDAEMON—HE MEETS WITH THEOCLYMENUS -AT PYLOS AND BRINGS HIM TO ITHACA—ON LANDING HE GOES TO THE HUT OF -EUMAEUS. - - -But Minerva went to the fair city of Lacedaemon to tell Ulysses’ son -that he was to return at once. She found him and Pisistratus sleeping -in the forecourt of Menelaus’s house; Pisistratus was fast asleep, but -Telemachus could get no rest all night for thinking of his unhappy -father, so Minerva went close up to him and said: - -“Telemachus, you should not remain so far away from home any longer, -nor leave your property with such dangerous people in your house; they -will eat up everything you have among them, and you will have been on a -fool’s errand. Ask Menelaus to send you home at once if you wish to -find your excellent mother still there when you get back. Her father -and brothers are already urging her to marry Eurymachus, who has given -her more than any of the others, and has been greatly increasing his -wedding presents. I hope nothing valuable may have been taken from the -house in spite of you, but you know what women are—they always want to -do the best they can for the man who marries them, and never give -another thought to the children of their first husband, nor to their -father either when he is dead and done with. Go home, therefore, and -put everything in charge of the most respectable woman servant that you -have, until it shall please heaven to send you a wife of your own. Let -me tell you also of another matter which you had better attend to. The -chief men among the suitors are lying in wait for you in the Strait128 -between Ithaca and Samos, and they mean to kill you before you can -reach home. I do not much think they will succeed; it is more likely -that some of those who are now eating up your property will find a -grave themselves. Sail night and day, and keep your ship well away from -the islands; the god who watches over you and protects you will send -you a fair wind. As soon as you get to Ithaca send your ship and men on -to the town, but yourself go straight to the swineherd who has charge -of your pigs; he is well disposed towards you, stay with him, -therefore, for the night, and then send him to Penelope to tell her -that you have got back safe from Pylos.” - -Then she went back to Olympus; but Telemachus stirred Pisistratus with -his heel to rouse him, and said, “Wake up Pisistratus, and yoke the -horses to the chariot, for we must set off home.”129 - -But Pisistratus said, “No matter what hurry we are in we cannot drive -in the dark. It will be morning soon; wait till Menelaus has brought -his presents and put them in the chariot for us; and let him say good -bye to us in the usual way. So long as he lives a guest should never -forget a host who has shown him kindness.” - -As he spoke day began to break, and Menelaus, who had already risen, -leaving Helen in bed, came towards them. When Telemachus saw him he put -on his shirt as fast as he could, threw a great cloak over his -shoulders, and went out to meet him. “Menelaus,” said he, “let me go -back now to my own country, for I want to get home.” - -And Menelaus answered, “Telemachus, if you insist on going I will not -detain you. I do not like to see a host either too fond of his guest or -too rude to him. Moderation is best in all things, and not letting a -man go when he wants to do so is as bad as telling him to go if he -would like to stay. One should treat a guest well as long as he is in -the house and speed him when he wants to leave it. Wait, then, till I -can get your beautiful presents into your chariot, and till you have -yourself seen them. I will tell the women to prepare a sufficient -dinner for you of what there may be in the house; it will be at once -more proper and cheaper for you to get your dinner before setting out -on such a long journey. If, moreover, you have a fancy for making a -tour in Hellas or in the Peloponnese, I will yoke my horses, and will -conduct you myself through all our principal cities. No one will send -us away empty handed; every one will give us something—a bronze tripod, -a couple of mules, or a gold cup.” - -“Menelaus,” replied Telemachus, “I want to go home at once, for when I -came away I left my property without protection, and fear that while -looking for my father I shall come to ruin myself, or find that -something valuable has been stolen during my absence.” - -When Menelaus heard this he immediately told his wife and servants to -prepare a sufficient dinner from what there might be in the house. At -this moment Eteoneus joined him, for he lived close by and had just got -up; so Menelaus told him to light the fire and cook some meat, which he -at once did. Then Menelaus went down into his fragrant store room,130 -not alone, but Helen went too, with Megapenthes. When he reached the -place where the treasures of his house were kept, he selected a double -cup, and told his son Megapenthes to bring also a silver mixing bowl. -Meanwhile Helen went to the chest where she kept the lovely dresses -which she had made with her own hands, and took out one that was -largest and most beautifully enriched with embroidery; it glittered -like a star, and lay at the very bottom of the chest. 131 Then they all -came back through the house again till they got to Telemachus, and -Menelaus said, “Telemachus, may Jove, the mighty husband of Juno, bring -you safely home according to your desire. I will now present you with -the finest and most precious piece of plate in all my house. It is a -mixing bowl of pure silver, except the rim, which is inlaid with gold, -and it is the work of Vulcan. Phaedimus king of the Sidonians made me a -present of it in the course of a visit that I paid him while I was on -my return home. I should like to give it to you.” - -With these words he placed the double cup in the hands of Telemachus, -while Megapenthes brought the beautiful mixing bowl and set it before -him. Hard by stood lovely Helen with the robe ready in her hand. - -“I too, my son,” said she, “have something for you as a keepsake from -the hand of Helen; it is for your bride to wear upon her wedding day. -Till then, get your dear mother to keep it for you; thus may you go -back rejoicing to your own country and to your home.” - -So saying she gave the robe over to him and he received it gladly. Then -Pisistratus put the presents into the chariot, and admired them all as -he did so. Presently Menelaus took Telemachus and Pisistratus into the -house, and they both of them sat down to table. A maid servant brought -them water in a beautiful golden ewer, and poured it into a silver -basin for them to wash their hands, and she drew a clean table beside -them; an upper servant brought them bread and offered them many good -things of what there was in the house. Eteoneus carved the meat and -gave them each their portions, while Megapenthes poured out the wine. -Then they laid their hands upon the good things that were before them, -but as soon as they had had enough to eat and drink Telemachus and -Pisistratus yoked the horses, and took their places in the chariot. -They drove out through the inner gateway and under the echoing -gatehouse of the outer court, and Menelaus came after them with a -golden goblet of wine in his right hand that they might make a -drink-offering before they set out. He stood in front of the horses and -pledged them, saying, “Farewell to both of you; see that you tell -Nestor how I have treated you, for he was as kind to me as any father -could be while we Achaeans were fighting before Troy.” - -“We will be sure, sir,” answered Telemachus, “to tell him everything as -soon as we see him. I wish I were as certain of finding Ulysses -returned when I get back to Ithaca, that I might tell him of the very -great kindness you have shown me and of the many beautiful presents I -am taking with me.” - -As he was thus speaking a bird flew on his right hand—an eagle with a -great white goose in its talons which it had carried off from the farm -yard—and all the men and women were running after it and shouting. It -came quite close up to them and flew away on their right hands in front -of the horses. When they saw it they were glad, and their hearts took -comfort within them, whereon Pisistratus said, “Tell me, Menelaus, has -heaven sent this omen for us or for you?” - -Menelaus was thinking what would be the most proper answer for him to -make, but Helen was too quick for him and said, “I will read this -matter as heaven has put it in my heart, and as I doubt not that it -will come to pass. The eagle came from the mountain where it was bred -and has its nest, and in like manner Ulysses, after having travelled -far and suffered much, will return to take his revenge—if indeed he is -not back already and hatching mischief for the suitors.” - -“May Jove so grant it,” replied Telemachus, “if it should prove to be -so, I will make vows to you as though you were a god, even when I am at -home.” - -As he spoke he lashed his horses and they started off at full speed -through the town towards the open country. They swayed the yoke upon -their necks and travelled the whole day long till the sun set and -darkness was over all the land. Then they reached Pherae, where Diocles -lived who was son of Ortilochus, the son of Alpheus. There they passed -the night and were treated hospitably. When the child of morning, -rosy-fingered Dawn, appeared, they again yoked their horses and their -places in the chariot. They drove out through the inner gateway and -under the echoing gatehouse of the outer court. Then Pisistratus lashed -his horses on and they flew forward nothing loath; ere long they came -to Pylos, and then Telemachus said: - -“Pisistratus, I hope you will promise to do what I am going to ask you. -You know our fathers were old friends before us; moreover, we are both -of an age, and this journey has brought us together still more closely; -do not, therefore, take me past my ship, but leave me there, for if I -go to your father’s house he will try to keep me in the warmth of his -good will towards me, and I must go home at once.” - -Pisistratus thought how he should do as he was asked, and in the end he -deemed it best to turn his horses towards the ship, and put Menelaus’s -beautiful presents of gold and raiment in the stern of the vessel. Then -he said, “Go on board at once and tell your men to do so also before I -can reach home to tell my father. I know how obstinate he is, and am -sure he will not let you go; he will come down here to fetch you, and -he will not go back without you. But he will be very angry.” - -With this he drove his goodly steeds back to the city of the Pylians -and soon reached his home, but Telemachus called the men together and -gave his orders. “Now, my men,” said he, “get everything in order on -board the ship, and let us set out home.” - -Thus did he speak, and they went on board even as he had said. But as -Telemachus was thus busied, praying also and sacrificing to Minerva in -the ship’s stern, there came to him a man from a distant country, a -seer, who was flying from Argos because he had killed a man. He was -descended from Melampus, who used to live in Pylos, the land of sheep; -he was rich and owned a great house, but he was driven into exile by -the great and powerful king Neleus. Neleus seized his goods and held -them for a whole year, during which he was a close prisoner in the -house of king Phylacus, and in much distress of mind both on account of -the daughter of Neleus and because he was haunted by a great sorrow -that dread Erinys had laid upon him. In the end, however, he escaped -with his life, drove the cattle from Phylace to Pylos, avenged the -wrong that had been done him, and gave the daughter of Neleus to his -brother. Then he left the country and went to Argos, where it was -ordained that he should reign over much people. There he married, -established himself, and had two famous sons Antiphates and Mantius. -Antiphates became father of Oicleus, and Oicleus of Amphiaraus, who was -dearly loved both by Jove and by Apollo, but he did not live to old -age, for he was killed in Thebes by reason of a woman’s gifts. His sons -were Alcmaeon and Amphilochus. Mantius, the other son of Melampus, was -father to Polypheides and Cleitus. Aurora, throned in gold, carried off -Cleitus for his beauty’s sake, that he might dwell among the immortals, -but Apollo made Polypheides the greatest seer in the whole world now -that Amphiaraus was dead. He quarrelled with his father and went to -live in Hyperesia, where he remained and prophesied for all men. - -His son, Theoclymenus, it was who now came up to Telemachus as he was -making drink-offerings and praying in his ship. “Friend,” said he, “now -that I find you sacrificing in this place, I beseech you by your -sacrifices themselves, and by the god to whom you make them, I pray you -also by your own head and by those of your followers tell me the truth -and nothing but the truth. Who and whence are you? Tell me also of your -town and parents.” - -Telemachus said, “I will answer you quite truly. I am from Ithaca, and -my father is Ulysses, as surely as that he ever lived. But he has come -to some miserable end. Therefore I have taken this ship and got my crew -together to see if I can hear any news of him, for he has been away a -long time.” - -“I too,” answered Theoclymenus, “am an exile, for I have killed a man -of my own race. He has many brothers and kinsmen in Argos, and they -have great power among the Argives. I am flying to escape death at -their hands, and am thus doomed to be a wanderer on the face of the -earth. I am your suppliant; take me, therefore, on board your ship that -they may not kill me, for I know they are in pursuit.” - -“I will not refuse you,” replied Telemachus, “if you wish to join us. -Come, therefore, and in Ithaca we will treat you hospitably according -to what we have.” - -On this he received Theoclymenus’ spear and laid it down on the deck of -the ship. He went on board and sat in the stern, bidding Theoclymenus -sit beside him; then the men let go the hawsers. Telemachus told them -to catch hold of the ropes, and they made all haste to do so. They set -the mast in its socket in the cross plank, raised it and made it fast -with the forestays, and they hoisted their white sails with sheets of -twisted ox hide. Minerva sent them a fair wind that blew fresh and -strong to take the ship on her course as fast as possible. Thus then -they passed by Crouni and Chalcis. - -Presently the sun set and darkness was over all the land. The vessel -made a quick passage to Pheae and thence on to Elis, where the Epeans -rule. Telemachus then headed her for the flying islands,132 wondering -within himself whether he should escape death or should be taken -prisoner. - -Meanwhile Ulysses and the swineherd were eating their supper in the -hut, and the men supped with them. As soon as they had had to eat and -drink, Ulysses began trying to prove the swineherd and see whether he -would continue to treat him kindly, and ask him to stay on at the -station or pack him off to the city; so he said: - -“Eumaeus, and all of you, to-morrow I want to go away and begin begging -about the town, so as to be no more trouble to you or to your men. Give -me your advice therefore, and let me have a good guide to go with me -and show me the way. I will go the round of the city begging as I needs -must, to see if any one will give me a drink and a piece of bread. I -should like also to go to the house of Ulysses and bring news of her -husband to Queen Penelope. I could then go about among the suitors and -see if out of all their abundance they will give me a dinner. I should -soon make them an excellent servant in all sorts of ways. Listen and -believe when I tell you that by the blessing of Mercury who gives grace -and good name to the works of all men, there is no one living who would -make a more handy servant than I should—to put fresh wood on the fire, -chop fuel, carve, cook, pour out wine, and do all those services that -poor men have to do for their betters.” - -The swineherd was very much disturbed when he heard this. “Heaven help -me,” he exclaimed, “what ever can have put such a notion as that into -your head? If you go near the suitors you will be undone to a -certainty, for their pride and insolence reach the very heavens. They -would never think of taking a man like you for a servant. Their -servants are all young men, well dressed, wearing good cloaks and -shirts, with well looking faces and their hair always tidy, the tables -are kept quite clean and are loaded with bread, meat, and wine. Stay -where you are, then; you are not in anybody’s way; I do not mind your -being here, no more do any of the others, and when Telemachus comes -home he will give you a shirt and cloak and will send you wherever you -want to go.” - -Ulysses answered, “I hope you may be as dear to the gods as you are to -me, for having saved me from going about and getting into trouble; -there is nothing worse than being always on the tramp; still, when men -have once got low down in the world they will go through a great deal -on behalf of their miserable bellies. Since, however, you press me to -stay here and await the return of Telemachus, tell me about Ulysses’ -mother, and his father whom he left on the threshold of old age when he -set out for Troy. Are they still living or are they already dead and in -the house of Hades?” - -“I will tell you all about them,” replied Eumaeus, “Laertes is still -living and prays heaven to let him depart peacefully in his own house, -for he is terribly distressed about the absence of his son, and also -about the death of his wife, which grieved him greatly and aged him -more than anything else did. She came to an unhappy end133 through -sorrow for her son: may no friend or neighbour who has dealt kindly by -me come to such an end as she did. As long as she was still living, -though she was always grieving, I used to like seeing her and asking -her how she did, for she brought me up along with her daughter Ctimene, -the youngest of her children; we were boy and girl together, and she -made little difference between us. When, however, we both grew up, they -sent Ctimene to Same and received a splendid dowry for her. As for me, -my mistress gave me a good shirt and cloak with a pair of sandals for -my feet, and sent me off into the country, but she was just as fond of -me as ever. This is all over now. Still it has pleased heaven to -prosper my work in the situation which I now hold. I have enough to eat -and drink, and can find something for any respectable stranger who -comes here; but there is no getting a kind word or deed out of my -mistress, for the house has fallen into the hands of wicked people. -Servants want sometimes to see their mistress and have a talk with her; -they like to have something to eat and drink at the house, and -something too to take back with them into the country. This is what -will keep servants in a good humour.” - -Ulysses answered, “Then you must have been a very little fellow, -Eumaeus, when you were taken so far away from your home and parents. -Tell me, and tell me true, was the city in which your father and mother -lived sacked and pillaged, or did some enemies carry you off when you -were alone tending sheep or cattle, ship you off here, and sell you for -whatever your master gave them?” - -“Stranger,” replied Eumaeus, “as regards your question: sit still, make -yourself comfortable, drink your wine, and listen to me. The nights are -now at their longest; there is plenty of time both for sleeping and -sitting up talking together; you ought not to go to bed till bed time, -too much sleep is as bad as too little; if any one of the others wishes -to go to bed let him leave us and do so; he can then take my master’s -pigs out when he has done breakfast in the morning. We too will sit -here eating and drinking in the hut, and telling one another stories -about our misfortunes; for when a man has suffered much, and been -buffeted about in the world, he takes pleasure in recalling the memory -of sorrows that have long gone by. As regards your question, then, my -tale is as follows: - -“You may have heard of an island called Syra that lies over above -Ortygia,134 where the land begins to turn round and look in another -direction.135 It is not very thickly peopled, but the soil is good, -with much pasture fit for cattle and sheep, and it abounds with wine -and wheat. Dearth never comes there, nor are the people plagued by any -sickness, but when they grow old Apollo comes with Diana and kills them -with his painless shafts. It contains two communities, and the whole -country is divided between these two. My father Ctesius son of Ormenus, -a man comparable to the gods, reigned over both. - -“Now to this place there came some cunning traders from Phoenicia (for -the Phoenicians are great mariners) in a ship which they had freighted -with gewgaws of all kinds. There happened to be a Phoenician woman in -my father’s house, very tall and comely, and an excellent servant; -these scoundrels got hold of her one day when she was washing near -their ship, seduced her, and cajoled her in ways that no woman can -resist, no matter how good she may be by nature. The man who had -seduced her asked her who she was and where she came from, and on this -she told him her father’s name. ‘I come from Sidon,’ said she, ‘and am -daughter to Arybas, a man rolling in wealth. One day as I was coming -into the town from the country, some Taphian pirates seized me and took -me here over the sea, where they sold me to the man who owns this -house, and he gave them their price for me.’ - -“The man who had seduced her then said, ‘Would you like to come along -with us to see the house of your parents and your parents themselves? -They are both alive and are said to be well off.’ - -“‘I will do so gladly,’ answered she, ‘if you men will first swear me a -solemn oath that you will do me no harm by the way.’ - -“They all swore as she told them, and when they had completed their -oath the woman said, ‘Hush; and if any of your men meets me in the -street or at the well, do not let him speak to me, for fear some one -should go and tell my master, in which case he would suspect something. -He would put me in prison, and would have all of you murdered; keep -your own counsel therefore; buy your merchandise as fast as you can, -and send me word when you have done loading. I will bring as much gold -as I can lay my hands on, and there is something else also that I can -do towards paying my fare. I am nurse to the son of the good man of the -house, a funny little fellow just able to run about. I will carry him -off in your ship, and you will get a great deal of money for him if you -take him and sell him in foreign parts.’ - -“On this she went back to the house. The Phoenicians stayed a whole -year till they had loaded their ship with much precious merchandise, -and then, when they had got freight enough, they sent to tell the -woman. Their messenger, a very cunning fellow, came to my father’s -house bringing a necklace of gold with amber beads strung among it; and -while my mother and the servants had it in their hands admiring it and -bargaining about it, he made a sign quietly to the woman and then went -back to the ship, whereon she took me by the hand and led me out of the -house. In the fore part of the house she saw the tables set with the -cups of guests who had been feasting with my father, as being in -attendance on him; these were now all gone to a meeting of the public -assembly, so she snatched up three cups and carried them off in the -bosom of her dress, while I followed her, for I knew no better. The sun -was now set, and darkness was over all the land, so we hurried on as -fast as we could till we reached the harbour, where the Phoenician ship -was lying. When they had got on board they sailed their ways over the -sea, taking us with them, and Jove sent then a fair wind; six days did -we sail both night and day, but on the seventh day Diana struck the -woman and she fell heavily down into the ship’s hold as though she were -a sea gull alighting on the water; so they threw her overboard to the -seals and fishes, and I was left all sorrowful and alone. Presently the -winds and waves took the ship to Ithaca, where Laertes gave sundry of -his chattels for me, and thus it was that ever I came to set eyes upon -this country.” - -Ulysses answered, “Eumaeus, I have heard the story of your misfortunes -with the most lively interest and pity, but Jove has given you good as -well as evil, for in spite of everything you have a good master, who -sees that you always have enough to eat and drink; and you lead a good -life, whereas I am still going about begging my way from city to city.” - -Thus did they converse, and they had only a very little time left for -sleep, for it was soon daybreak. In the mean time Telemachus and his -crew were nearing land, so they loosed the sails, took down the mast, -and rowed the ship into the harbour.136 They cast out their mooring -stones and made fast the hawsers; they then got out upon the sea shore, -mixed their wine, and got dinner ready. As soon as they had had enough -to eat and drink Telemachus said, “Take the ship on to the town, but -leave me here, for I want to look after the herdsmen on one of my -farms. In the evening, when I have seen all I want, I will come down to -the city, and to-morrow morning in return for your trouble I will give -you all a good dinner with meat and wine.” 137 - -Then Theoclymenus said, “And what, my dear young friend, is to become -of me? To whose house, among all your chief men, am I to repair? or -shall I go straight to your own house and to your mother?” - -“At any other time,” replied Telemachus, “I should have bidden you go -to my own house, for you would find no want of hospitality; at the -present moment, however, you would not be comfortable there, for I -shall be away, and my mother will not see you; she does not often show -herself even to the suitors, but sits at her loom weaving in an upper -chamber, out of their way; but I can tell you a man whose house you can -go to—I mean Eurymachus the son of Polybus, who is held in the highest -estimation by every one in Ithaca. He is much the best man and the most -persistent wooer, of all those who are paying court to my mother and -trying to take Ulysses’ place. Jove, however, in heaven alone knows -whether or no they will come to a bad end before the marriage takes -place.” - -As he was speaking a bird flew by upon his right hand—a hawk, Apollo’s -messenger. It held a dove in its talons, and the feathers, as it tore -them off,138 fell to the ground midway between Telemachus and the ship. -On this Theoclymenus called him apart and caught him by the hand. -“Telemachus,” said he, “that bird did not fly on your right hand -without having been sent there by some god. As soon as I saw it I knew -it was an omen; it means that you will remain powerful and that there -will be no house in Ithaca more royal than your own.” - -“I wish it may prove so,” answered Telemachus. “If it does, I will show -you so much good will and give you so many presents that all who meet -you will congratulate you.” - -Then he said to his friend Piraeus, “Piraeus, son of Clytius, you have -throughout shown yourself the most willing to serve me of all those who -have accompanied me to Pylos; I wish you would take this stranger to -your own house and entertain him hospitably till I can come for him.” - -And Piraeus answered, “Telemachus, you may stay away as long as you -please, but I will look after him for you, and he shall find no lack of -hospitality.” - -As he spoke he went on board, and bade the others do so also and loose -the hawsers, so they took their places in the ship. But Telemachus -bound on his sandals, and took a long and doughty spear with a head of -sharpened bronze from the deck of the ship. Then they loosed the -hawsers, thrust the ship off from land, and made on towards the city as -they had been told to do, while Telemachus strode on as fast as he -could, till he reached the homestead where his countless herds of swine -were feeding, and where dwelt the excellent swineherd, who was so -devoted a servant to his master. - - - - -BOOK XVI - - -ULYSSES REVEALS HIMSELF TO TELEMACHUS. - - -Meanwhile Ulysses and the swineherd had lit a fire in the hut and were -were getting breakfast ready at daybreak, for they had sent the men out -with the pigs. When Telemachus came up, the dogs did not bark but -fawned upon him, so Ulysses, hearing the sound of feet and noticing -that the dogs did not bark, said to Eumaeus: - -“Eumaeus, I hear footsteps; I suppose one of your men or some one of -your acquaintance is coming here, for the dogs are fawning upon him and -not barking.” - -The words were hardly out of his mouth before his son stood at the -door. Eumaeus sprang to his feet, and the bowls in which he was mixing -wine fell from his hands, as he made towards his master. He kissed his -head and both his beautiful eyes, and wept for joy. A father could not -be more delighted at the return of an only son, the child of his old -age, after ten years’ absence in a foreign country and after having -gone through much hardship. He embraced him, kissed him all over as -though he had come back from the dead, and spoke fondly to him saying: - -“So you are come, Telemachus, light of my eyes that you are. When I -heard you had gone to Pylos I made sure I was never going to see you -any more. Come in, my dear child, and sit down, that I may have a good -look at you now you are home again; it is not very often you come into -the country to see us herdsmen; you stick pretty close to the town -generally. I suppose you think it better to keep an eye on what the -suitors are doing.” - -“So be it, old friend,” answered Telemachus, “but I am come now because -I want to see you, and to learn whether my mother is still at her old -home or whether some one else has married her, so that the bed of -Ulysses is without bedding and covered with cobwebs.” - -“She is still at the house,” replied Eumaeus, “grieving and breaking -her heart, and doing nothing but weep, both night and day continually.” - -As he spoke he took Telemachus’ spear, whereon he crossed the stone -threshold and came inside. Ulysses rose from his seat to give him place -as he entered, but Telemachus checked him; “Sit down, stranger,” said -he, “I can easily find another seat, and there is one here who will lay -it for me.” - -Ulysses went back to his own place, and Eumaeus strewed some green -brushwood on the floor and threw a sheepskin on top of it for -Telemachus to sit upon. Then the swineherd brought them platters of -cold meat, the remains from what they had eaten the day before, and he -filled the bread baskets with bread as fast as he could. He mixed wine -also in bowls of ivy-wood, and took his seat facing Ulysses. Then they -laid their hands on the good things that were before them, and as soon -as they had had enough to eat and drink Telemachus said to Eumaeus, -“Old friend, where does this stranger come from? How did his crew bring -him to Ithaca, and who were they?—for assuredly he did not come here by -land.” - -To this you answered, O swineherd Eumaeus, “My son, I will tell you the -real truth. He says he is a Cretan, and that he has been a great -traveller. At this moment he is running away from a Thesprotian ship, -and has taken refuge at my station, so I will put him into your hands. -Do whatever you like with him, only remember that he is your -suppliant.” - -“I am very much distressed,” said Telemachus, “by what you have just -told me. How can I take this stranger into my house? I am as yet young, -and am not strong enough to hold my own if any man attacks me. My -mother cannot make up her mind whether to stay where she is and look -after the house out of respect for public opinion and the memory of her -husband, or whether the time is now come for her to take the best man -of those who are wooing her, and the one who will make her the most -advantageous offer; still, as the stranger has come to your station I -will find him a cloak and shirt of good wear, with a sword and sandals, -and will send him wherever he wants to go. Or if you like you can keep -him here at the station, and I will send him clothes and food that he -may be no burden on you and on your men; but I will not have him go -near the suitors, for they are very insolent, and are sure to ill treat -him in a way that would greatly grieve me; no matter how valiant a man -may be he can do nothing against numbers, for they will be too strong -for him.” - -Then Ulysses said, “Sir, it is right that I should say something -myself. I am much shocked about what you have said about the insolent -way in which the suitors are behaving in despite of such a man as you -are. Tell me, do you submit to such treatment tamely, or has some god -set your people against you? May you not complain of your brothers—for -it is to these that a man may look for support, however great his -quarrel may be? I wish I were as young as you are and in my present -mind; if I were son to Ulysses, or, indeed, Ulysses himself, I would -rather some one came and cut my head off, but I would go to the house -and be the bane of every one of these men.139 If they were too many for -me—I being single-handed—I would rather die fighting in my own house -than see such disgraceful sights day after day, strangers grossly -maltreated, and men dragging the women servants about the house in an -unseemly way, wine drawn recklessly, and bread wasted all to no purpose -for an end that shall never be accomplished.” - -And Telemachus answered, “I will tell you truly everything. There is no -enmity between me and my people, nor can I complain of brothers, to -whom a man may look for support however great his quarrel may be. Jove -has made us a race of only sons. Laertes was the only son of Arceisius, -and Ulysses only son of Laertes. I am myself the only son of Ulysses -who left me behind him when he went away, so that I have never been of -any use to him. Hence it comes that my house is in the hands of -numberless marauders; for the chiefs from all the neighbouring islands, -Dulichium, Same, Zacynthus, as also all the principal men of Ithaca -itself, are eating up my house under the pretext of paying court to my -mother, who will neither say point blank that she will not marry, nor -yet bring matters to an end, so they are making havoc of my estate, and -before long will do so with myself into the bargain. The issue, -however, rests with heaven. But do you, old friend Eumaeus, go at once -and tell Penelope that I am safe and have returned from Pylos. Tell it -to herself alone, and then come back here without letting any one else -know, for there are many who are plotting mischief against me.” - -“I understand and heed you,” replied Eumaeus; “you need instruct me no -further, only as I am going that way say whether I had not better let -poor Laertes know that you are returned. He used to superintend the -work on his farm in spite of his bitter sorrow about Ulysses, and he -would eat and drink at will along with his servants; but they tell me -that from the day on which you set out for Pylos he has neither eaten -nor drunk as he ought to do, nor does he look after his farm, but sits -weeping and wasting the flesh from off his bones.” - -“More’s the pity,” answered Telemachus, “I am sorry for him, but we -must leave him to himself just now. If people could have everything -their own way, the first thing I should choose would be the return of -my father; but go, and give your message; then make haste back again, -and do not turn out of your way to tell Laertes. Tell my mother to send -one of her women secretly with the news at once, and let him hear it -from her.” - -Thus did he urge the swineherd; Eumaeus, therefore, took his sandals, -bound them to his feet, and started for the town. Minerva watched him -well off the station, and then came up to it in the form of a -woman—fair, stately, and wise. She stood against the side of the entry, -and revealed herself to Ulysses, but Telemachus could not see her, and -knew not that she was there, for the gods do not let themselves be seen -by everybody. Ulysses saw her, and so did the dogs, for they did not -bark, but went scared and whining off to the other side of the yards. -She nodded her head and motioned to Ulysses with her eyebrows; whereon -he left the hut and stood before her outside the main wall of the -yards. Then she said to him: - -“Ulysses, noble son of Laertes, it is now time for you to tell your -son: do not keep him in the dark any longer, but lay your plans for the -destruction of the suitors, and then make for the town. I will not be -long in joining you, for I too am eager for the fray.” - -As she spoke she touched him with her golden wand. First she threw a -fair clean shirt and cloak about his shoulders; then she made him -younger and of more imposing presence; she gave him back his colour, -filled out his cheeks, and let his beard become dark again. Then she -went away and Ulysses came back inside the hut. His son was astounded -when he saw him, and turned his eyes away for fear he might be looking -upon a god. - -“Stranger,” said he, “how suddenly you have changed from what you were -a moment or two ago. You are dressed differently and your colour is not -the same. Are you some one or other of the gods that live in heaven? If -so, be propitious to me till I can make you due sacrifice and offerings -of wrought gold. Have mercy upon me.” - -And Ulysses said, “I am no god, why should you take me for one? I am -your father, on whose account you grieve and suffer so much at the -hands of lawless men.” - -As he spoke he kissed his son, and a tear fell from his cheek on to the -ground, for he had restrained all tears till now. But Telemachus could -not yet believe that it was his father, and said: - -“You are not my father, but some god is flattering me with vain hopes -that I may grieve the more hereafter; no mortal man could of himself -contrive to do as you have been doing, and make yourself old and young -at a moment’s notice, unless a god were with him. A second ago you were -old and all in rags, and now you are like some god come down from -heaven.” - -Ulysses answered, “Telemachus, you ought not to be so immeasurably -astonished at my being really here. There is no other Ulysses who will -come hereafter. Such as I am, it is I, who after long wandering and -much hardship have got home in the twentieth year to my own country. -What you wonder at is the work of the redoubtable goddess Minerva, who -does with me whatever she will, for she can do what she pleases. At one -moment she makes me like a beggar, and the next I am a young man with -good clothes on my back; it is an easy matter for the gods who live in -heaven to make any man look either rich or poor.” - -As he spoke he sat down, and Telemachus threw his arms about his father -and wept. They were both so much moved that they cried aloud like -eagles or vultures with crooked talons that have been robbed of their -half fledged young by peasants. Thus piteously did they weep, and the -sun would have gone down upon their mourning if Telemachus had not -suddenly said, “In what ship, my dear father, did your crew bring you -to Ithaca? Of what nation did they declare themselves to be—for you -cannot have come by land?” - -“I will tell you the truth, my son,” replied Ulysses. “It was the -Phaeacians who brought me here. They are great sailors, and are in the -habit of giving escorts to any one who reaches their coasts. They took -me over the sea while I was fast asleep, and landed me in Ithaca, after -giving me many presents in bronze, gold, and raiment. These things by -heaven’s mercy are lying concealed in a cave, and I am now come here on -the suggestion of Minerva that we may consult about killing our -enemies. First, therefore, give me a list of the suitors, with their -number, that I may learn who, and how many, they are. I can then turn -the matter over in my mind, and see whether we two can fight the whole -body of them ourselves, or whether we must find others to help us.” - -To this Telemachus answered, “Father, I have always heard of your -renown both in the field and in council, but the task you talk of is a -very great one: I am awed at the mere thought of it; two men cannot -stand against many and brave ones. There are not ten suitors only, nor -twice ten, but ten many times over; you shall learn their number at -once. There are fifty-two chosen youths from Dulichium, and they have -six servants; from Same there are twenty-four; twenty young Achaeans -from Zacynthus, and twelve from Ithaca itself, all of them well born. -They have with them a servant Medon, a bard, and two men who can carve -at table. If we face such numbers as this, you may have bitter cause to -rue your coming, and your revenge. See whether you cannot think of some -one who would be willing to come and help us.” - -“Listen to me,” replied Ulysses, “and think whether Minerva and her -father Jove may seem sufficient, or whether I am to try and find some -one else as well.” - -“Those whom you have named,” answered Telemachus, “are a couple of good -allies, for though they dwell high up among the clouds they have power -over both gods and men.” - -“These two,” continued Ulysses, “will not keep long out of the fray, -when the suitors and we join fight in my house. Now, therefore, return -home early to-morrow morning, and go about among the suitors as before. -Later on the swineherd will bring me to the city disguised as a -miserable old beggar. If you see them ill treating me, steel your heart -against my sufferings; even though they drag me feet foremost out of -the house, or throw things at me, look on and do nothing beyond gently -trying to make them behave more reasonably; but they will not listen to -you, for the day of their reckoning is at hand. Furthermore I say, and -lay my saying to your heart; when Minerva shall put it in my mind, I -will nod my head to you, and on seeing me do this you must collect all -the armour that is in the house and hide it in the strong store room. -Make some excuse when the suitors ask you why you are removing it; say -that you have taken it to be out of the way of the smoke, inasmuch as -it is no longer what it was when Ulysses went away, but has become -soiled and begrimed with soot. Add to this more particularly that you -are afraid Jove may set them on to quarrel over their wine, and that -they may do each other some harm which may disgrace both banquet and -wooing, for the sight of arms sometimes tempts people to use them. But -leave a sword and a spear apiece for yourself and me, and a couple of -oxhide shields so that we can snatch them up at any moment; Jove and -Minerva will then soon quiet these people. There is also another -matter; if you are indeed my son and my blood runs in your veins, let -no one know that Ulysses is within the house—neither Laertes, nor yet -the swineherd, nor any of the servants, nor even Penelope herself. Let -you and me exploit the women alone, and let us also make trial of some -other of the men servants, to see who is on our side and whose hand is -against us.” - -“Father,” replied Telemachus, “you will come to know me by and by, and -when you do you will find that I can keep your counsel. I do not think, -however, the plan you propose will turn out well for either of us. -Think it over. It will take us a long time to go the round of the farms -and exploit the men, and all the time the suitors will be wasting your -estate with impunity and without compunction. Prove the women by all -means, to see who are disloyal and who guiltless, but I am not in -favour of going round and trying the men. We can attend to that later -on, if you really have some sign from Jove that he will support you.” - -Thus did they converse, and meanwhile the ship which had brought -Telemachus and his crew from Pylos had reached the town of Ithaca. When -they had come inside the harbour they drew the ship on to the land; -their servants came and took their armour from them, and they left all -the presents at the house of Clytius. Then they sent a servant to tell -Penelope that Telemachus had gone into the country, but had sent the -ship to the town to prevent her from being alarmed and made unhappy. -This servant and Eumaeus happened to meet when they were both on the -same errand of going to tell Penelope. When they reached the House, the -servant stood up and said to the queen in the presence of the waiting -women, “Your son, Madam, is now returned from Pylos”; but Eumaeus went -close up to Penelope, and said privately all that her son had bidden -him tell her. When he had given his message he left the house with its -outbuildings and went back to his pigs again. - -The suitors were surprised and angry at what had happened, so they went -outside the great wall that ran round the outer court, and held a -council near the main entrance. Eurymachus, son of Polybus, was the -first to speak. - -“My friends,” said he, “this voyage of Telemachus’s is a very serious -matter; we had made sure that it would come to nothing. Now, however, -let us draw a ship into the water, and get a crew together to send -after the others and tell them to come back as fast as they can.” - -He had hardly done speaking when Amphinomus turned in his place and saw -the ship inside the harbour, with the crew lowering her sails, and -putting by their oars; so he laughed, and said to the others, “We need -not send them any message, for they are here. Some god must have told -them, or else they saw the ship go by, and could not overtake her.” - -On this they rose and went to the water side. The crew then drew the -ship on shore; their servants took their armour from them, and they -went up in a body to the place of assembly, but they would not let any -one old or young sit along with them, and Antinous, son of Eupeithes, -spoke first. - -“Good heavens,” said he, “see how the gods have saved this man from -destruction. We kept a succession of scouts upon the headlands all day -long, and when the sun was down we never went on shore to sleep, but -waited in the ship all night till morning in the hope of capturing and -killing him; but some god has conveyed him home in spite of us. Let us -consider how we can make an end of him. He must not escape us; our -affair is never likely to come off while he is alive, for he is very -shrewd, and public feeling is by no means all on our side. We must make -haste before he can call the Achaeans in assembly; he will lose no time -in doing so, for he will be furious with us, and will tell all the -world how we plotted to kill him, but failed to take him. The people -will not like this when they come to know of it; we must see that they -do us no hurt, nor drive us from our own country into exile. Let us try -and lay hold of him either on his farm away from the town, or on the -road hither. Then we can divide up his property amongst us, and let his -mother and the man who marries her have the house. If this does not -please you, and you wish Telemachus to live on and hold his father’s -property, then we must not gather here and eat up his goods in this -way, but must make our offers to Penelope each from his own house, and -she can marry the man who will give the most for her, and whose lot it -is to win her.” - -They all held their peace until Amphinomus rose to speak. He was the -son of Nisus, who was son to king Aretias, and he was foremost among -all the suitors from the wheat-growing and well grassed island of -Dulichium; his conversation, moreover, was more agreeable to Penelope -than that of any of the other suitors, for he was a man of good natural -disposition. “My friends,” said he, speaking to them plainly and in all -honestly, “I am not in favour of killing Telemachus. It is a heinous -thing to kill one who is of noble blood. Let us first take counsel of -the gods, and if the oracles of Jove advise it, I will both help to -kill him myself, and will urge everyone else to do so; but if they -dissuade us, I would have you hold your hands.” - -Thus did he speak, and his words pleased them well, so they rose -forthwith and went to the house of Ulysses, where they took their -accustomed seats. - -Then Penelope resolved that she would show herself to the suitors. She -knew of the plot against Telemachus, for the servant Medon had -overheard their counsels and had told her; she went down therefore to -the court attended by her maidens, and when she reached the suitors she -stood by one of the bearing-posts supporting the roof of the cloister -holding a veil before her face, and rebuked Antinous saying: - -“Antinous, insolent and wicked schemer, they say you are the best -speaker and counsellor of any man your own age in Ithaca, but you are -nothing of the kind. Madman, why should you try to compass the death of -Telemachus, and take no heed of suppliants, whose witness is Jove -himself? It is not right for you to plot thus against one another. Do -you not remember how your father fled to this house in fear of the -people, who were enraged against him for having gone with some Taphian -pirates and plundered the Thesprotians who were at peace with us? They -wanted to tear him in pieces and eat up everything he had, but Ulysses -stayed their hands although they were infuriated, and now you devour -his property without paying for it, and break my heart by wooing his -wife and trying to kill his son. Leave off doing so, and stop the -others also.” - -To this Eurymachus son of Polybus answered, “Take heart, Queen Penelope -daughter of Icarius, and do not trouble yourself about these matters. -The man is not yet born, nor never will be, who shall lay hands upon -your son Telemachus, while I yet live to look upon the face of the -earth. I say—and it shall surely be—that my spear shall be reddened -with his blood; for many a time has Ulysses taken me on his knees, held -wine up to my lips to drink, and put pieces of meat into my hands. -Therefore Telemachus is much the dearest friend I have, and has nothing -to fear from the hands of us suitors. Of course, if death comes to him -from the gods, he cannot escape it.” He said this to quiet her, but in -reality he was plotting against Telemachus. - -Then Penelope went upstairs again and mourned her husband till Minerva -shed sleep over her eyes. In the evening Eumaeus got back to Ulysses -and his son, who had just sacrificed a young pig of a year old and were -helping one another to get supper ready; Minerva therefore came up to -Ulysses, turned him into an old man with a stroke of her wand, and clad -him in his old clothes again, for fear that the swineherd might -recognise him and not keep the secret, but go and tell Penelope. - -Telemachus was the first to speak. “So you have got back, Eumaeus,” -said he. “What is the news of the town? Have the suitors returned, or -are they still waiting over yonder, to take me on my way home?” - -“I did not think of asking about that,” replied Eumaeus, “when I was in -the town. I thought I would give my message and come back as soon as I -could. I met a man sent by those who had gone with you to Pylos, and he -was the first to tell the news to your mother, but I can say what I saw -with my own eyes; I had just got on to the crest of the hill of Mercury -above the town when I saw a ship coming into harbour with a number of -men in her. They had many shields and spears, and I thought it was the -suitors, but I cannot be sure.” - -On hearing this Telemachus smiled to his father, but so that Eumaeus -could not see him. - -Then, when they had finished their work and the meal was ready, they -ate it, and every man had his full share so that all were satisfied. As -soon as they had had enough to eat and drink, they laid down to rest -and enjoyed the boon of sleep. - - - - -BOOK XVII - - -TELEMACHUS AND HIS MOTHER MEET—ULYSSES AND EUMAEUS COME DOWN TO THE -TOWN, AND ULYSSES IS INSULTED BY MELANTHIUS—HE IS RECOGNISED BY THE DOG -ARGOS—HE IS INSULTED AND PRESENTLY STRUCK BY ANTINOUS WITH A -STOOL—PENELOPE DESIRES THAT HE SHALL BE SENT TO HER. - - -When the child of morning, rosy-fingered Dawn, appeared, Telemachus -bound on his sandals and took a strong spear that suited his hands, for -he wanted to go into the city. “Old friend,” said he to the swineherd, -“I will now go to the town and show myself to my mother, for she will -never leave off grieving till she has seen me. As for this unfortunate -stranger, take him to the town and let him beg there of any one who -will give him a drink and a piece of bread. I have trouble enough of my -own, and cannot be burdened with other people. If this makes him angry -so much the worse for him, but I like to say what I mean.” - -Then Ulysses said, “Sir, I do not want to stay here; a beggar can -always do better in town than country, for any one who likes can give -him something. I am too old to care about remaining here at the beck -and call of a master. Therefore let this man do as you have just told -him, and take me to the town as soon as I have had a warm by the fire, -and the day has got a little heat in it. My clothes are wretchedly -thin, and this frosty morning I shall be perished with cold, for you -say the city is some way off.” - -On this Telemachus strode off through the yards, brooding his revenge -upon the suitors. When he reached home he stood his spear against a -bearing-post of the cloister, crossed the stone floor of the cloister -itself, and went inside. - -Nurse Euryclea saw him long before any one else did. She was putting -the fleeces on to the seats, and she burst out crying as she ran up to -him; all the other maids came up too, and covered his head and -shoulders with their kisses. Penelope came out of her room looking like -Diana or Venus, and wept as she flung her arms about her son. She -kissed his forehead and both his beautiful eyes, “Light of my eyes,” -she cried as she spoke fondly to him, “so you are come home again; I -made sure I was never going to see you any more. To think of your -having gone off to Pylos without saying anything about it or obtaining -my consent. But come, tell me what you saw.” - -“Do not scold me, mother,” answered Telemachus, “nor vex me, seeing -what a narrow escape I have had, but wash your face, change your dress, -go upstairs with your maids, and promise full and sufficient hecatombs -to all the gods if Jove will only grant us our revenge upon the -suitors. I must now go to the place of assembly to invite a stranger -who has come back with me from Pylos. I sent him on with my crew, and -told Piraeus to take him home and look after him till I could come for -him myself.” - -She heeded her son’s words, washed her face, changed her dress, and -vowed full and sufficient hecatombs to all the gods if they would only -vouchsafe her revenge upon the suitors. - -Telemachus went through, and out of, the cloisters spear in hand—not -alone, for his two fleet dogs went with him. Minerva endowed him with a -presence of such divine comeliness that all marvelled at him as he went -by, and the suitors gathered round him with fair words in their mouths -and malice in their hearts; but he avoided them, and went to sit with -Mentor, Antiphus, and Halitherses, old friends of his father’s house, -and they made him tell them all that had happened to him. Then Piraeus -came up with Theoclymenus, whom he had escorted through the town to the -place of assembly, whereon Telemachus at once joined them. Piraeus was -first to speak: “Telemachus,” said he, “I wish you would send some of -your women to my house to take away the presents Menelaus gave you.” - -“We do not know, Piraeus,” answered Telemachus, “what may happen. If -the suitors kill me in my own house and divide my property among them, -I would rather you had the presents than that any of those people -should get hold of them. If on the other hand I managed to kill them, I -shall be much obliged if you will kindly bring me my presents.” - -With these words he took Theoclymenus to his own house. When they got -there they laid their cloaks on the benches and seats, went into the -baths, and washed themselves. When the maids had washed and anointed -them, and had given them cloaks and shirts, they took their seats at -table. A maid servant then brought them water in a beautiful golden -ewer, and poured it into a silver basin for them to wash their hands; -and she drew a clean table beside them. An upper servant brought them -bread and offered them many good things of what there was in the house. -Opposite them sat Penelope, reclining on a couch by one of the -bearing-posts of the cloister, and spinning. Then they laid their hands -on the good things that were before them, and as soon as they had had -enough to eat and drink Penelope said: - -“Telemachus, I shall go upstairs and lie down on that sad couch, which -I have not ceased to water with my tears, from the day Ulysses set out -for Troy with the sons of Atreus. You failed, however, to make it clear -to me before the suitors came back to the house, whether or no you had -been able to hear anything about the return of your father.” - -“I will tell you then truth,” replied her son. “We went to Pylos and -saw Nestor, who took me to his house and treated me as hospitably as -though I were a son of his own who had just returned after a long -absence; so also did his sons; but he said he had not heard a word from -any human being about Ulysses, whether he was alive or dead. He sent -me, therefore, with a chariot and horses to Menelaus. There I saw -Helen, for whose sake so many, both Argives and Trojans, were in -heaven’s wisdom doomed to suffer. Menelaus asked me what it was that -had brought me to Lacedaemon, and I told him the whole truth, whereon -he said, ‘So, then, these cowards would usurp a brave man’s bed? A hind -might as well lay her new-born young in the lair of a lion, and then go -off to feed in the forest or in some grassy dell. The lion, when he -comes back to his lair, will make short work with the pair of them, and -so will Ulysses with these suitors. By father Jove, Minerva, and -Apollo, if Ulysses is still the man that he was when he wrestled with -Philomeleides in Lesbos, and threw him so heavily that all the Greeks -cheered him—if he is still such, and were to come near these suitors, -they would have a short shrift and a sorry wedding. As regards your -question, however, I will not prevaricate nor deceive you, but what the -old man of the sea told me, so much will I tell you in full. He said he -could see Ulysses on an island sorrowing bitterly in the house of the -nymph Calypso, who was keeping him prisoner, and he could not reach his -home, for he had no ships nor sailors to take him over the sea.’ This -was what Menelaus told me, and when I had heard his story I came away; -the gods then gave me a fair wind and soon brought me safe home again.” - -With these words he moved the heart of Penelope. Then Theoclymenus said -to her: - -“Madam, wife of Ulysses, Telemachus does not understand these things; -listen therefore to me, for I can divine them surely, and will hide -nothing from you. May Jove the king of heaven be my witness, and the -rites of hospitality, with that hearth of Ulysses to which I now come, -that Ulysses himself is even now in Ithaca, and, either going about the -country or staying in one place, is enquiring into all these evil deeds -and preparing a day of reckoning for the suitors. I saw an omen when I -was on the ship which meant this, and I told Telemachus about it.” - -“May it be even so,” answered Penelope; “if your words come true, you -shall have such gifts and such good will from me that all who see you -shall congratulate you.” - -Thus did they converse. Meanwhile the suitors were throwing discs, or -aiming with spears at a mark on the levelled ground in front of the -house, and behaving with all their old insolence. But when it was now -time for dinner, and the flock of sheep and goats had come into the -town from all the country round, 140 with their shepherds as usual, -then Medon, who was their favourite servant, and who waited upon them -at table, said, “Now then, my young masters, you have had enough sport, -so come inside that we may get dinner ready. Dinner is not a bad thing, -at dinner time.” - -They left their sports as he told them, and when they were within the -house, they laid their cloaks on the benches and seats inside, and then -sacrificed some sheep, goats, pigs, and a heifer, all of them fat and -well grown.141 Thus they made ready for their meal. In the meantime -Ulysses and the swineherd were about starting for the town, and the -swineherd said, “Stranger, I suppose you still want to go to town -to-day, as my master said you were to do; for my own part I should have -liked you to stay here as a station hand, but I must do as my master -tells me, or he will scold me later on, and a scolding from one’s -master is a very serious thing. Let us then be off, for it is now broad -day; it will be night again directly and then you will find it -colder.”142 - -“I know, and understand you,” replied Ulysses; “you need say no more. -Let us be going, but if you have a stick ready cut, let me have it to -walk with, for you say the road is a very rough one.” - -As he spoke he threw his shabby old tattered wallet over his shoulders, -by the cord from which it hung, and Eumaeus gave him a stick to his -liking. The two then started, leaving the station in charge of the dogs -and herdsmen who remained behind; the swineherd led the way and his -master followed after, looking like some broken down old tramp as he -leaned upon his staff, and his clothes were all in rags. When they had -got over the rough steep ground and were nearing the city, they reached -the fountain from which the citizens drew their water. This had been -made by Ithacus, Neritus, and Polyctor. There was a grove of -water-loving poplars planted in a circle all round it, and the clear -cold water came down to it from a rock high up,143 while above the -fountain there was an altar to the nymphs, at which all wayfarers used -to sacrifice. Here Melanthius son of Dolius overtook them as he was -driving down some goats, the best in his flock, for the suitors’ -dinner, and there were two shepherds with him. When he saw Eumaeus and -Ulysses he reviled them with outrageous and unseemly language, which -made Ulysses very angry. - -“There you go,” cried he, “and a precious pair you are. See how heaven -brings birds of the same feather to one another. Where, pray, master -swineherd, are you taking this poor miserable object? It would make any -one sick to see such a creature at table. A fellow like this never won -a prize for anything in his life, but will go about rubbing his -shoulders against every man’s door post, and begging, not for swords -and cauldrons144 like a man, but only for a few scraps not worth -begging for. If you would give him to me for a hand on my station, he -might do to clean out the folds, or bring a bit of sweet feed to the -kids, and he could fatten his thighs as much as he pleased on whey; but -he has taken to bad ways and will not go about any kind of work; he -will do nothing but beg victuals all the town over, to feed his -insatiable belly. I say, therefore—and it shall surely be—if he goes -near Ulysses’ house he will get his head broken by the stools they will -fling at him, till they turn him out.” - -On this, as he passed, he gave Ulysses a kick on the hip out of pure -wantonness, but Ulysses stood firm, and did not budge from the path. -For a moment he doubted whether or no to fly at Melanthius and kill him -with his staff, or fling him to the ground and beat his brains out; he -resolved, however, to endure it and keep himself in check, but the -swineherd looked straight at Melanthius and rebuked him, lifting up his -hands and praying to heaven as he did so. - -“Fountain nymphs,” he cried, “children of Jove, if ever Ulysses burned -you thigh bones covered with fat whether of lambs or kids, grant my -prayer that heaven may send him home. He would soon put an end to the -swaggering threats with which such men as you go about insulting -people—gadding all over the town while your flocks are going to ruin -through bad shepherding.” - -Then Melanthius the goatherd answered, “You ill conditioned cur, what -are you talking about? Some day or other I will put you on board ship -and take you to a foreign country, where I can sell you and pocket the -money you will fetch. I wish I were as sure that Apollo would strike -Telemachus dead this very day, or that the suitors would kill him, as I -am that Ulysses will never come home again.” - -With this he left them to come on at their leisure, while he went -quickly forward and soon reached the house of his master. When he got -there he went in and took his seat among the suitors opposite -Eurymachus, who liked him better than any of the others. The servants -brought him a portion of meat, and an upper woman servant set bread -before him that he might eat. Presently Ulysses and the swineherd came -up to the house and stood by it, amid a sound of music, for Phemius was -just beginning to sing to the suitors. Then Ulysses took hold of the -swineherd’s hand, and said: - -“Eumaeus, this house of Ulysses is a very fine place. No matter how far -you go, you will find few like it. One building keeps following on -after another. The outer court has a wall with battlements all round -it; the doors are double folding, and of good workmanship; it would be -a hard matter to take it by force of arms. I perceive, too, that there -are many people banqueting within it, for there is a smell of roast -meat, and I hear a sound of music, which the gods have made to go along -with feasting.” - -Then Eumaeus said, “You have perceived aright, as indeed you generally -do; but let us think what will be our best course. Will you go inside -first and join the suitors, leaving me here behind you, or will you -wait here and let me go in first? But do not wait long, or some one may -see you loitering about outside, and throw something at you. Consider -this matter I pray you.” - -And Ulysses answered, “I understand and heed. Go in first and leave me -here where I am. I am quite used to being beaten and having things -thrown at me. I have been so much buffeted about in war and by sea that -I am case-hardened, and this too may go with the rest. But a man cannot -hide away the cravings of a hungry belly; this is an enemy which gives -much trouble to all men; it is because of this that ships are fitted -out to sail the seas, and to make war upon other people.” - -As they were thus talking, a dog that had been lying asleep raised his -head and pricked up his ears. This was Argos, whom Ulysses had bred -before setting out for Troy, but he had never had any work out of him. -In the old days he used to be taken out by the young men when they went -hunting wild goats, or deer, or hares, but now that his master was gone -he was lying neglected on the heaps of mule and cow dung that lay in -front of the stable doors till the men should come and draw it away to -manure the great close; and he was full of fleas. As soon as he saw -Ulysses standing there, he dropped his ears and wagged his tail, but he -could not get close up to his master. When Ulysses saw the dog on the -other side of the yard, he dashed a tear from his eyes without Eumaeus -seeing it, and said: - -“Eumaeus, what a noble hound that is over yonder on the manure heap: -his build is splendid; is he as fine a fellow as he looks, or is he -only one of those dogs that come begging about a table, and are kept -merely for show?” - -“This hound,” answered Eumaeus, “belonged to him who has died in a far -country. If he were what he was when Ulysses left for Troy, he would -soon show you what he could do. There was not a wild beast in the -forest that could get away from him when he was once on its tracks. But -now he has fallen on evil times, for his master is dead and gone, and -the women take no care of him. Servants never do their work when their -master’s hand is no longer over them, for Jove takes half the goodness -out of a man when he makes a slave of him.” - -As he spoke he went inside the buildings to the cloister where the -suitors were, but Argos died as soon as he had recognised his master. - -Telemachus saw Eumaeus long before any one else did, and beckoned him -to come and sit beside him; so he looked about and saw a seat lying -near where the carver sat serving out their portions to the suitors; he -picked it up, brought it to Telemachus’s table, and sat down opposite -him. Then the servant brought him his portion, and gave him bread from -the bread-basket. - -Immediately afterwards Ulysses came inside, looking like a poor -miserable old beggar, leaning on his staff and with his clothes all in -rags. He sat down upon the threshold of ash-wood just inside the doors -leading from the outer to the inner court, and against a bearing-post -of cypress-wood which the carpenter had skilfully planed, and had made -to join truly with rule and line. Telemachus took a whole loaf from the -bread-basket, with as much meat as he could hold in his two hands, and -said to Eumaeus, “Take this to the stranger, and tell him to go the -round of the suitors, and beg from them; a beggar must not be -shamefaced.” - -So Eumaeus went up to him and said, “Stranger, Telemachus sends you -this, and says you are to go the round of the suitors begging, for -beggars must not be shamefaced.” - -Ulysses answered, “May King Jove grant all happiness to Telemachus, and -fulfil the desire of his heart.” - -Then with both hands he took what Telemachus had sent him, and laid it -on the dirty old wallet at his feet. He went on eating it while the -bard was singing, and had just finished his dinner as he left off. The -suitors applauded the bard, whereon Minerva went up to Ulysses and -prompted him to beg pieces of bread from each one of the suitors, that -he might see what kind of people they were, and tell the good from the -bad; but come what might she was not going to save a single one of -them. Ulysses, therefore, went on his round, going from left to right, -and stretched out his hands to beg as though he were a real beggar. -Some of them pitied him, and were curious about him, asking one another -who he was and where he came from; whereon the goatherd Melanthius -said, “Suitors of my noble mistress, I can tell you something about -him, for I have seen him before. The swineherd brought him here, but I -know nothing about the man himself, nor where he comes from.” - -On this Antinous began to abuse the swineherd. “You precious idiot,” he -cried, “what have you brought this man to town for? Have we not tramps -and beggars enough already to pester us as we sit at meat? Do you think -it a small thing that such people gather here to waste your master’s -property—and must you needs bring this man as well?” - -And Eumaeus answered, “Antinous, your birth is good but your words -evil. It was no doing of mine that he came here. Who is likely to -invite a stranger from a foreign country, unless it be one of those who -can do public service as a seer, a healer of hurts, a carpenter, or a -bard who can charm us with his singing? Such men are welcome all the -world over, but no one is likely to ask a beggar who will only worry -him. You are always harder on Ulysses’ servants than any of the other -suitors are, and above all on me, but I do not care so long as -Telemachus and Penelope are alive and here.” - -But Telemachus said, “Hush, do not answer him; Antinous has the -bitterest tongue of all the suitors, and he makes the others worse.” - -Then turning to Antinous he said, “Antinous, you take as much care of -my interests as though I were your son. Why should you want to see this -stranger turned out of the house? Heaven forbid; take something and -give it him yourself; I do not grudge it; I bid you take it. Never mind -my mother, nor any of the other servants in the house; but I know you -will not do what I say, for you are more fond of eating things yourself -than of giving them to other people.” - -“What do you mean, Telemachus,” replied Antinous, “by this swaggering -talk? If all the suitors were to give him as much as I will, he would -not come here again for another three months.” - -As he spoke he drew the stool on which he rested his dainty feet from -under the table, and made as though he would throw it at Ulysses, but -the other suitors all gave him something, and filled his wallet with -bread and meat; he was about, therefore, to go back to the threshold -and eat what the suitors had given him, but he first went up to -Antinous and said: - -“Sir, give me something; you are not, surely, the poorest man here; you -seem to be a chief, foremost among them all; therefore you should be -the better giver, and I will tell far and wide of your bounty. I too -was a rich man once, and had a fine house of my own; in those days I -gave to many a tramp such as I now am, no matter who he might be nor -what he wanted. I had any number of servants, and all the other things -which people have who live well and are accounted wealthy, but it -pleased Jove to take all away from me. He sent me with a band of roving -robbers to Egypt; it was a long voyage and I was undone by it. I -stationed my ships in the river Aegyptus, and bade my men stay by them -and keep guard over them, while I sent out scouts to reconnoitre from -every point of vantage. - -“But the men disobeyed my orders, took to their own devices, and -ravaged the land of the Egyptians, killing the men, and taking their -wives and children captives. The alarm was soon carried to the city, -and when they heard the war-cry, the people came out at daybreak till -the plain was filled with soldiers horse and foot, and with the gleam -of armour. Then Jove spread panic among my men, and they would no -longer face the enemy, for they found themselves surrounded. The -Egyptians killed many of us, and took the rest alive to do forced -labour for them; as for myself, they gave me to a friend who met them, -to take to Cyprus, Dmetor by name, son of Iasus, who was a great man in -Cyprus. Thence I am come hither in a state of great misery.” - -Then Antinous said, “What god can have sent such a pestilence to plague -us during our dinner? Get out, into the open part of the court,145 or I -will give you Egypt and Cyprus over again for your insolence and -importunity; you have begged of all the others, and they have given you -lavishly, for they have abundance round them, and it is easy to be free -with other people’s property when there is plenty of it.” - -On this Ulysses began to move off, and said, “Your looks, my fine sir, -are better than your breeding; if you were in your own house you would -not spare a poor man so much as a pinch of salt, for though you are in -another man’s, and surrounded with abundance, you cannot find it in you -to give him even a piece of bread.” - -This made Antinous very angry, and he scowled at him saying, “You shall -pay for this before you get clear of the court.” With these words he -threw a footstool at him, and hit him on the right shoulder blade near -the top of his back. Ulysses stood firm as a rock and the blow did not -even stagger him, but he shook his head in silence as he brooded on his -revenge. Then he went back to the threshold and sat down there, laying -his well filled wallet at his feet. - -“Listen to me,” he cried, “you suitors of Queen Penelope, that I may -speak even as I am minded. A man knows neither ache nor pain if he gets -hit while fighting for his money, or for his sheep or his cattle; and -even so Antinous has hit me while in the service of my miserable belly, -which is always getting people into trouble. Still, if the poor have -gods and avenging deities at all, I pray them that Antinous may come to -a bad end before his marriage.” - -“Sit where you are, and eat your victuals in silence, or be off -elsewhere,” shouted Antinous. “If you say more I will have you dragged -hand and foot through the courts, and the servants shall flay you -alive.” - -The other suitors were much displeased at this, and one of the young -men said, “Antinous, you did ill in striking that poor wretch of a -tramp: it will be worse for you if he should turn out to be some -god—and we know the gods go about disguised in all sorts of ways as -people from foreign countries, and travel about the world to see who do -amiss and who righteously.”146 - -Thus said the suitors, but Antinous paid them no heed. Meanwhile -Telemachus was furious about the blow that had been given to his -father, and though no tear fell from him, he shook his head in silence -and brooded on his revenge. - -Now when Penelope heard that the beggar had been struck in the -banqueting-cloister, she said before her maids, “Would that Apollo -would so strike you, Antinous,” and her waiting woman Eurynome -answered, “If our prayers were answered not one of the suitors would -ever again see the sun rise.” Then Penelope said, “Nurse,147 I hate -every single one of them, for they mean nothing but mischief, but I -hate Antinous like the darkness of death itself. A poor unfortunate -tramp has come begging about the house for sheer want. Every one else -has given him something to put in his wallet, but Antinous has hit him -on the right shoulder-blade with a footstool.” - -Thus did she talk with her maids as she sat in her own room, and in the -meantime Ulysses was getting his dinner. Then she called for the -swineherd and said, “Eumaeus, go and tell the stranger to come here, I -want to see him and ask him some questions. He seems to have travelled -much, and he may have seen or heard something of my unhappy husband.” - -To this you answered, O swineherd Eumaeus, “If these Achaeans, Madam, -would only keep quiet, you would be charmed with the history of his -adventures. I had him three days and three nights with me in my hut, -which was the first place he reached after running away from his ship, -and he has not yet completed the story of his misfortunes. If he had -been the most heaven-taught minstrel in the whole world, on whose lips -all hearers hang entranced, I could not have been more charmed as I sat -in my hut and listened to him. He says there is an old friendship -between his house and that of Ulysses, and that he comes from Crete -where the descendants of Minos live, after having been driven hither -and thither by every kind of misfortune; he also declares that he has -heard of Ulysses as being alive and near at hand among the -Thesprotians, and that he is bringing great wealth home with him.” - -“Call him here, then,” said Penelope, “that I too may hear his story. -As for the suitors, let them take their pleasure indoors or out as they -will, for they have nothing to fret about. Their corn and wine remain -unwasted in their houses with none but servants to consume them, while -they keep hanging about our house day after day sacrificing our oxen, -sheep, and fat goats for their banquets, and never giving so much as a -thought to the quantity of wine they drink. No estate can stand such -recklessness, for we have now no Ulysses to protect us. If he were to -come again, he and his son would soon have their revenge.” - -As she spoke Telemachus sneezed so loudly that the whole house -resounded with it. Penelope laughed when she heard this, and said to -Eumaeus, “Go and call the stranger; did you not hear how my son sneezed -just as I was speaking? This can only mean that all the suitors are -going to be killed, and that not one of them shall escape. Furthermore -I say, and lay my saying to your heart: if I am satisfied that the -stranger is speaking the truth I shall give him a shirt and cloak of -good wear.” - -When Eumaeus heard this he went straight to Ulysses and said, “Father -stranger, my mistress Penelope, mother of Telemachus, has sent for you; -she is in great grief, but she wishes to hear anything you can tell her -about her husband, and if she is satisfied that you are speaking the -truth, she will give you a shirt and cloak, which are the very things -that you are most in want of. As for bread, you can get enough of that -to fill your belly, by begging about the town, and letting those give -that will.” - -“I will tell Penelope,” answered Ulysses, “nothing but what is strictly -true. I know all about her husband, and have been partner with him in -affliction, but I am afraid of passing through this crowd of cruel -suitors, for their pride and insolence reach heaven. Just now, -moreover, as I was going about the house without doing any harm, a man -gave me a blow that hurt me very much, but neither Telemachus nor any -one else defended me. Tell Penelope, therefore, to be patient and wait -till sundown. Let her give me a seat close up to the fire, for my -clothes are worn very thin—you know they are, for you have seen them -ever since I first asked you to help me—she can then ask me about the -return of her husband.” - -The swineherd went back when he heard this, and Penelope said as she -saw him cross the threshold, “Why do you not bring him here, Eumaeus? -Is he afraid that some one will ill-treat him, or is he shy of coming -inside the house at all? Beggars should not be shamefaced.” - -To this you answered, O swineherd Eumaeus, “The stranger is quite -reasonable. He is avoiding the suitors, and is only doing what any one -else would do. He asks you to wait till sundown, and it will be much -better, madam, that you should have him all to yourself, when you can -hear him and talk to him as you will.” - -“The man is no fool,” answered Penelope, “it would very likely be as he -says, for there are no such abominable people in the whole world as -these men are.” - -When she had done speaking Eumaeus went back to the suitors, for he had -explained everything. Then he went up to Telemachus and said in his ear -so that none could overhear him, “My dear sir, I will now go back to -the pigs, to see after your property and my own business. You will look -to what is going on here, but above all be careful to keep out of -danger, for there are many who bear you ill will. May Jove bring them -to a bad end before they do us a mischief.” - -“Very well,” replied Telemachus, “go home when you have had your -dinner, and in the morning come here with the victims we are to -sacrifice for the day. Leave the rest to heaven and me.” - -On this Eumaeus took his seat again, and when he had finished his -dinner he left the courts and the cloister with the men at table, and -went back to his pigs. As for the suitors, they presently began to -amuse themselves with singing and dancing, for it was now getting on -towards evening. - - - - -BOOK XVIII - - -THE FIGHT WITH IRUS—ULYSSES WARNS AMPHINOMUS—PENELOPE GETS PRESENTS -FROM THE SUITORS—THE BRAZIERS—ULYSSES REBUKES EURYMACHUS. - - -Now there came a certain common tramp who used to go begging all over -the city of Ithaca, and was notorious as an incorrigible glutton and -drunkard. This man had no strength nor stay in him, but he was a great -hulking fellow to look at; his real name, the one his mother gave him, -was Arnaeus, but the young men of the place called him Irus,148 because -he used to run errands for any one who would send him. As soon as he -came he began to insult Ulysses, and to try and drive him out of his -own house. - -“Be off, old man,” he cried, “from the doorway, or you shall be dragged -out neck and heels. Do you not see that they are all giving me the -wink, and wanting me to turn you out by force, only I do not like to do -so? Get up then, and go of yourself, or we shall come to blows.” - -Ulysses frowned on him and said, “My friend, I do you no manner of -harm; people give you a great deal, but I am not jealous. There is room -enough in this doorway for the pair of us, and you need not grudge me -things that are not yours to give. You seem to be just such another -tramp as myself, but perhaps the gods will give us better luck by and -by. Do not, however, talk too much about fighting or you will incense -me, and old though I am, I shall cover your mouth and chest with blood. -I shall have more peace tomorrow if I do, for you will not come to the -house of Ulysses any more.” - -Irus was very angry and answered, “You filthy glutton, you run on -trippingly like an old fish-fag. I have a good mind to lay both hands -about you, and knock your teeth out of your head like so many boar’s -tusks. Get ready, therefore, and let these people here stand by and -look on. You will never be able to fight one who is so much younger -than yourself.” - -Thus roundly did they rate one another on the smooth pavement in front -of the doorway,149 and when Antinous saw what was going on he laughed -heartily and said to the others, “This is the finest sport that you -ever saw; heaven never yet sent anything like it into this house. The -stranger and Irus have quarreled and are going to fight, let us set -them on to do so at once.” - -The suitors all came up laughing, and gathered round the two ragged -tramps. “Listen to me,” said Antinous, “there are some goats’ paunches -down at the fire, which we have filled with blood and fat, and set -aside for supper; he who is victorious and proves himself to be the -better man shall have his pick of the lot; he shall be free of our -table and we will not allow any other beggar about the house at all.” - -The others all agreed, but Ulysses, to throw them off the scent, said, -“Sirs, an old man like myself, worn out with suffering, cannot hold his -own against a young one; but my irrepressible belly urges me on, though -I know it can only end in my getting a drubbing. You must swear, -however that none of you will give me a foul blow to favour Irus and -secure him the victory.” - -They swore as he told them, and when they had completed their oath -Telemachus put in a word and said, “Stranger, if you have a mind to -settle with this fellow, you need not be afraid of any one here. -Whoever strikes you will have to fight more than one. I am host, and -the other chiefs, Antinous and Eurymachus, both of them men of -understanding, are of the same mind as I am.” - -Every one assented, and Ulysses girded his old rags about his loins, -thus baring his stalwart thighs, his broad chest and shoulders, and his -mighty arms; but Minerva came up to him and made his limbs even -stronger still. The suitors were beyond measure astonished, and one -would turn towards his neighbour saying, “The stranger has brought such -a thigh out of his old rags that there will soon be nothing left of -Irus.” - -Irus began to be very uneasy as he heard them, but the servants girded -him by force, and brought him [into the open part of the court] in such -a fright that his limbs were all of a tremble. Antinous scolded him and -said, “You swaggering bully, you ought never to have been born at all -if you are afraid of such an old broken down creature as this tramp is. -I say, therefore—and it shall surely be—if he beats you and proves -himself the better man, I shall pack you off on board ship to the -mainland and send you to king Echetus, who kills every one that comes -near him. He will cut off your nose and ears, and draw out your -entrails for the dogs to eat.” - -This frightened Irus still more, but they brought him into the middle -of the court, and the two men raised their hands to fight. Then Ulysses -considered whether he should let drive so hard at him as to make an end -of him then and there, or whether he should give him a lighter blow -that should only knock him down; in the end he deemed it best to give -the lighter blow for fear the Achaeans should begin to suspect who he -was. Then they began to fight, and Irus hit Ulysses on the right -shoulder; but Ulysses gave Irus a blow on the neck under the ear that -broke in the bones of his skull, and the blood came gushing out of his -mouth; he fell groaning in the dust, gnashing his teeth and kicking on -the ground, but the suitors threw up their hands and nearly died of -laughter, as Ulysses caught hold of him by the foot and dragged him -into the outer court as far as the gate-house. There he propped him up -against the wall and put his staff in his hands. “Sit here,” said he, -“and keep the dogs and pigs off; you are a pitiful creature, and if you -try to make yourself king of the beggars any more you shall fare still -worse.” - -Then he threw his dirty old wallet, all tattered and torn over his -shoulder with the cord by which it hung, and went back to sit down upon -the threshold; but the suitors went within the cloisters, laughing and -saluting him, “May Jove, and all the other gods,” said they, “grant you -whatever you want for having put an end to the importunity of this -insatiable tramp. We will take him over to the mainland presently, to -king Echetus, who kills every one that comes near him.” - -Ulysses hailed this as of good omen, and Antinous set a great goat’s -paunch before him filled with blood and fat. Amphinomus took two loaves -out of the bread-basket and brought them to him, pledging him as he did -so in a golden goblet of wine. “Good luck to you,” he said, “father -stranger, you are very badly off at present, but I hope you will have -better times by and by.” - -To this Ulysses answered, “Amphinomus, you seem to be a man of good -understanding, as indeed you may well be, seeing whose son you are. I -have heard your father well spoken of; he is Nisus of Dulichium, a man -both brave and wealthy. They tell me you are his son, and you appear to -be a considerable person; listen, therefore, and take heed to what I am -saying. Man is the vainest of all creatures that have their being upon -earth. As long as heaven vouchsafes him health and strength, he thinks -that he shall come to no harm hereafter, and even when the blessed gods -bring sorrow upon him, he bears it as he needs must, and makes the best -of it; for God almighty gives men their daily minds day by day. I know -all about it, for I was a rich man once, and did much wrong in the -stubbornness of my pride, and in the confidence that my father and my -brothers would support me; therefore let a man fear God in all things -always, and take the good that heaven may see fit to send him without -vain glory. Consider the infamy of what these suitors are doing; see -how they are wasting the estate, and doing dishonour to the wife, of -one who is certain to return some day, and that, too, not long hence. -Nay, he will be here soon; may heaven send you home quietly first that -you may not meet with him in the day of his coming, for once he is here -the suitors and he will not part bloodlessly.” - -With these words he made a drink-offering, and when he had drunk he put -the gold cup again into the hands of Amphinomus, who walked away -serious and bowing his head, for he foreboded evil. But even so he did -not escape destruction, for Minerva had doomed him to fall by the hand -of Telemachus. So he took his seat again at the place from which he had -come. - -Then Minerva put it into the mind of Penelope to show herself to the -suitors, that she might make them still more enamoured of her, and win -still further honour from her son and husband. So she feigned a mocking -laugh and said, “Eurynome, I have changed my mind, and have a fancy to -show myself to the suitors although I detest them. I should like also -to give my son a hint that he had better not have anything more to do -with them. They speak fairly enough but they mean mischief.” - -“My dear child,” answered Eurynome, “all that you have said is true, go -and tell your son about it, but first wash yourself and anoint your -face. Do not go about with your cheeks all covered with tears; it is -not right that you should grieve so incessantly; for Telemachus, whom -you always prayed that you might live to see with a beard, is already -grown up.” - -“I know, Eurynome,” replied Penelope, “that you mean well, but do not -try and persuade me to wash and to anoint myself, for heaven robbed me -of all my beauty on the day my husband sailed; nevertheless, tell -Autonoe and Hippodamia that I want them. They must be with me when I am -in the cloister; I am not going among the men alone; it would not be -proper for me to do so.” - -On this the old woman150 went out of the room to bid the maids go to -their mistress. In the meantime Minerva bethought her of another -matter, and sent Penelope off into a sweet slumber; so she lay down on -her couch and her limbs became heavy with sleep. Then the goddess shed -grace and beauty over her that all the Achaeans might admire her. She -washed her face with the ambrosial loveliness that Venus wears when she -goes dancing with the Graces; she made her taller and of a more -commanding figure, while as for her complexion it was whiter than sawn -ivory. When Minerva had done all this she went away, whereon the maids -came in from the women’s room and woke Penelope with the sound of their -talking. - -“What an exquisitely delicious sleep I have been having,” said she, as -she passed her hands over her face, “in spite of all my misery. I wish -Diana would let me die so sweetly now at this very moment, that I might -no longer waste in despair for the loss of my dear husband, who -possessed every kind of good quality and was the most distinguished man -among the Achaeans.” - -With these words she came down from her upper room, not alone but -attended by two of her maidens, and when she reached the suitors she -stood by one of the bearing-posts supporting the roof of the cloister, -holding a veil before her face, and with a staid maid servant on either -side of her. As they beheld her the suitors were so overpowered and -became so desperately enamoured of her, that each one prayed he might -win her for his own bed fellow. - -“Telemachus,” said she, addressing her son, “I fear you are no longer -so discreet and well conducted as you used to be. When you were younger -you had a greater sense of propriety; now, however, that you are grown -up, though a stranger to look at you would take you for the son of a -well to do father as far as size and good looks go, your conduct is by -no means what it should be. What is all this disturbance that has been -going on, and how came you to allow a stranger to be so disgracefully -ill-treated? What would have happened if he had suffered serious injury -while a suppliant in our house? Surely this would have been very -discreditable to you.” - -“I am not surprised, my dear mother, at your displeasure,” replied -Telemachus, “I understand all about it and know when things are not as -they should be, which I could not do when I was younger; I cannot, -however, behave with perfect propriety at all times. First one and then -another of these wicked people here keeps driving me out of my mind, -and I have no one to stand by me. After all, however, this fight -between Irus and the stranger did not turn out as the suitors meant it -to do, for the stranger got the best of it. I wish Father Jove, -Minerva, and Apollo would break the neck of every one of these wooers -of yours, some inside the house and some out; and I wish they might all -be as limp as Irus is over yonder in the gate of the outer court. See -how he nods his head like a drunken man; he has had such a thrashing -that he cannot stand on his feet nor get back to his home, wherever -that may be, for he has no strength left in him.” - -Thus did they converse. Eurymachus then came up and said, “Queen -Penelope, daughter of Icarius, if all the Achaeans in Iasian Argos -could see you at this moment, you would have still more suitors in your -house by tomorrow morning, for you are the most admirable woman in the -whole world both as regards personal beauty and strength of -understanding.” - -To this Penelope replied, “Eurymachus, heaven robbed me of all my -beauty whether of face or figure when the Argives set sail for Troy and -my dear husband with them. If he were to return and look after my -affairs, I should both be more respected and show a better presence to -the world. As it is, I am oppressed with care, and with the afflictions -which heaven has seen fit to heap upon me. My husband foresaw it all, -and when he was leaving home he took my right wrist in his hand—‘Wife,’ -he said, ‘we shall not all of us come safe home from Troy, for the -Trojans fight well both with bow and spear. They are excellent also at -fighting from chariots, and nothing decides the issue of a fight sooner -than this. I know not, therefore, whether heaven will send me back to -you, or whether I may not fall over there at Troy. In the meantime do -you look after things here. Take care of my father and mother as at -present, and even more so during my absence, but when you see our son -growing a beard, then marry whom you will, and leave this your present -home.’ This is what he said and now it is all coming true. A night will -come when I shall have to yield myself to a marriage which I detest, -for Jove has taken from me all hope of happiness. This further grief, -moreover, cuts me to the very heart. You suitors are not wooing me -after the custom of my country. When men are courting a woman who they -think will be a good wife to them and who is of noble birth, and when -they are each trying to win her for himself, they usually bring oxen -and sheep to feast the friends of the lady, and they make her -magnificent presents, instead of eating up other people’s property -without paying for it.” - -This was what she said, and Ulysses was glad when he heard her trying -to get presents out of the suitors, and flattering them with fair words -which he knew she did not mean. - -Then Antinous said, “Queen Penelope, daughter of Icarius, take as many -presents as you please from any one who will give them to you; it is -not well to refuse a present; but we will not go about our business nor -stir from where we are, till you have married the best man among us -whoever he may be.” - -The others applauded what Antinous had said, and each one sent his -servant to bring his present. Antinous’s man returned with a large and -lovely dress most exquisitely embroidered. It had twelve beautifully -made brooch pins of pure gold with which to fasten it. Eurymachus -immediately brought her a magnificent chain of gold and amber beads -that gleamed like sunlight. Eurydamas’s two men returned with some -earrings fashioned into three brilliant pendants which glistened most -beautifully; while king Pisander son of Polyctor gave her a necklace of -the rarest workmanship, and every one else brought her a beautiful -present of some kind. - -Then the queen went back to her room upstairs, and her maids brought -the presents after her. Meanwhile the suitors took to singing and -dancing, and stayed till evening came. They danced and sang till it -grew dark; they then brought in three braziers151 to give light, and -piled them up with chopped firewood very old and dry, and they lit -torches from them, which the maids held up turn and turn about. Then -Ulysses said: - -“Maids, servants of Ulysses who has so long been absent, go to the -queen inside the house; sit with her and amuse her, or spin, and pick -wool. I will hold the light for all these people. They may stay till -morning, but shall not beat me, for I can stand a great deal.” - -The maids looked at one another and laughed, while pretty Melantho -began to gibe at him contemptuously. She was daughter to Dolius, but -had been brought up by Penelope, who used to give her toys to play -with, and looked after her when she was a child; but in spite of all -this she showed no consideration for the sorrows of her mistress, and -used to misconduct herself with Eurymachus, with whom she was in love. - -“Poor wretch,” said she, “are you gone clean out of your mind? Go and -sleep in some smithy, or place of public gossips, instead of chattering -here. Are you not ashamed of opening your mouth before your betters—so -many of them too? Has the wine been getting into your head, or do you -always babble in this way? You seem to have lost your wits because you -beat the tramp Irus; take care that a better man than he does not come -and cudgel you about the head till he pack you bleeding out of the -house.” - -“Vixen,” replied Ulysses, scowling at her, “I will go and tell -Telemachus what you have been saying, and he will have you torn limb -from limb.” - -With these words he scared the women, and they went off into the body -of the house. They trembled all over, for they thought he would do as -he said. But Ulysses took his stand near the burning braziers, holding -up torches and looking at the people—brooding the while on things that -should surely come to pass. - -But Minerva would not let the suitors for one moment cease their -insolence, for she wanted Ulysses to become even more bitter against -them; she therefore set Eurymachus son of Polybus on to gibe at him, -which made the others laugh. “Listen to me,” said he, “you suitors of -Queen Penelope, that I may speak even as I am minded. It is not for -nothing that this man has come to the house of Ulysses; I believe the -light has not been coming from the torches, but from his own head—for -his hair is all gone, every bit of it.” - -Then turning to Ulysses he said, “Stranger, will you work as a servant, -if I send you to the wolds and see that you are well paid? Can you -build a stone fence, or plant trees? I will have you fed all the year -round, and will find you in shoes and clothing. Will you go, then? Not -you; for you have got into bad ways, and do not want to work; you had -rather fill your belly by going round the country begging.” - -“Eurymachus,” answered Ulysses, “if you and I were to work one against -the other in early summer when the days are at their longest—give me a -good scythe, and take another yourself, and let us see which will last -the longer or mow the stronger, from dawn till dark when the mowing -grass is about. Or if you will plough against me, let us each take a -yoke of tawny oxen, well-mated and of great strength and endurance: -turn me into a four acre field, and see whether you or I can drive the -straighter furrow. If, again, war were to break out this day, give me a -shield, a couple of spears and a helmet fitting well upon my -temples—you would find me foremost in the fray, and would cease your -gibes about my belly. You are insolent and cruel, and think yourself a -great man because you live in a little world, and that a bad one. If -Ulysses comes to his own again, the doors of his house are wide, but -you will find them narrow when you try to fly through them.” - -Eurymachus was furious at all this. He scowled at him and cried, “You -wretch, I will soon pay you out for daring to say such things to me, -and in public too. Has the wine been getting into your head or do you -always babble in this way? You seem to have lost your wits because you -beat the tramp Irus.” With this he caught hold of a footstool, but -Ulysses sought protection at the knees of Amphinomus of Dulichium, for -he was afraid. The stool hit the cupbearer on his right hand and -knocked him down: the man fell with a cry flat on his back, and his -wine-jug fell ringing to the ground. The suitors in the covered -cloister were now in an uproar, and one would turn towards his -neighbour, saying, “I wish the stranger had gone somewhere else, bad -luck to him, for all the trouble he gives us. We cannot permit such -disturbance about a beggar; if such ill counsels are to prevail we -shall have no more pleasure at our banquet.” - -On this Telemachus came forward and said, “Sirs, are you mad? Can you -not carry your meat and your liquor decently? Some evil spirit has -possessed you. I do not wish to drive any of you away, but you have had -your suppers, and the sooner you all go home to bed the better.” - -The suitors bit their lips and marvelled at the boldness of his speech; -but Amphinomus the son of Nisus, who was son to Aretias, said, “Do not -let us take offence; it is reasonable, so let us make no answer. -Neither let us do violence to the stranger nor to any of Ulysses’ -servants. Let the cupbearer go round with the drink-offerings, that we -may make them and go home to our rest. As for the stranger, let us -leave Telemachus to deal with him, for it is to his house that he has -come.” - -Thus did he speak, and his saying pleased them well, so Mulius of -Dulichium, servant to Amphinomus, mixed them a bowl of wine and water -and handed it round to each of them man by man, whereon they made their -drink-offerings to the blessed gods: Then, when they had made their -drink-offerings and had drunk each one as he was minded, they took -their several ways each of them to his own abode. - - - - -BOOK XIX - - -TELEMACHUS AND ULYSSES REMOVE THE ARMOUR—ULYSSES INTERVIEWS -PENELOPE—EURYCLEA WASHES HIS FEET AND RECOGNISES THE SCAR ON HIS -LEG—PENELOPE TELLS HER DREAM TO ULYSSES. - - -Ulysses was left in the cloister, pondering on the means whereby with -Minerva’s help he might be able to kill the suitors. Presently he said -to Telemachus, “Telemachus, we must get the armour together and take it -down inside. Make some excuse when the suitors ask you why you have -removed it. Say that you have taken it to be out of the way of the -smoke, inasmuch as it is no longer what it was when Ulysses went away, -but has become soiled and begrimed with soot. Add to this more -particularly that you are afraid Jove may set them on to quarrel over -their wine, and that they may do each other some harm which may -disgrace both banquet and wooing, for the sight of arms sometimes -tempts people to use them.” - -Telemachus approved of what his father had said, so he called nurse -Euryclea and said, “Nurse, shut the women up in their room, while I -take the armour that my father left behind him down into the store -room. No one looks after it now my father is gone, and it has got all -smirched with soot during my own boyhood. I want to take it down where -the smoke cannot reach it.” - -“I wish, child,” answered Euryclea, “that you would take the management -of the house into your own hands altogether, and look after all the -property yourself. But who is to go with you and light you to the -store-room? The maids would have done so, but you would not let them.” - -“The stranger,” said Telemachus, “shall show me a light; when people -eat my bread they must earn it, no matter where they come from.” - -Euryclea did as she was told, and bolted the women inside their room. -Then Ulysses and his son made all haste to take the helmets, shields, -and spears inside; and Minerva went before them with a gold lamp in her -hand that shed a soft and brilliant radiance, whereon Telemachus said, -“Father, my eyes behold a great marvel: the walls, with the rafters, -crossbeams, and the supports on which they rest are all aglow as with a -flaming fire. Surely there is some god here who has come down from -heaven.” - -“Hush,” answered Ulysses, “hold your peace and ask no questions, for -this is the manner of the gods. Get you to your bed, and leave me here -to talk with your mother and the maids. Your mother in her grief will -ask me all sorts of questions.” - -On this Telemachus went by torch-light to the other side of the inner -court, to the room in which he always slept. There he lay in his bed -till morning, while Ulysses was left in the cloister pondering on the -means whereby with Minerva’s help he might be able to kill the suitors. - -Then Penelope came down from her room looking like Venus or Diana, and -they set her a seat inlaid with scrolls of silver and ivory near the -fire in her accustomed place. It had been made by Icmalius and had a -footstool all in one piece with the seat itself; and it was covered -with a thick fleece: on this she now sat, and the maids came from the -women’s room to join her. They set about removing the tables at which -the wicked suitors had been dining, and took away the bread that was -left, with the cups from which they had drunk. They emptied the embers -out of the braziers, and heaped much wood upon them to give both light -and heat; but Melantho began to rail at Ulysses a second time and said, -“Stranger, do you mean to plague us by hanging about the house all -night and spying upon the women? Be off, you wretch, outside, and eat -your supper there, or you shall be driven out with a firebrand.” - -Ulysses scowled at her and answered, “My good woman, why should you be -so angry with me? Is it because I am not clean, and my clothes are all -in rags, and because I am obliged to go begging about after the manner -of tramps and beggars generally? I too was a rich man once, and had a -fine house of my own; in those days I gave to many a tramp such as I -now am, no matter who he might be nor what he wanted. I had any number -of servants, and all the other things which people have who live well -and are accounted wealthy, but it pleased Jove to take all away from -me; therefore, woman, beware lest you too come to lose that pride and -place in which you now wanton above your fellows; have a care lest you -get out of favour with your mistress, and lest Ulysses should come -home, for there is still a chance that he may do so. Moreover, though -he be dead as you think he is, yet by Apollo’s will he has left a son -behind him, Telemachus, who will note anything done amiss by the maids -in the house, for he is now no longer in his boyhood.” - -Penelope heard what he was saying and scolded the maid, “Impudent -baggage,” said she, “I see how abominably you are behaving, and you -shall smart for it. You knew perfectly well, for I told you myself, -that I was going to see the stranger and ask him about my husband, for -whose sake I am in such continual sorrow.” - -Then she said to her head waiting woman Eurynome, “Bring a seat with a -fleece upon it, for the stranger to sit upon while he tells his story, -and listens to what I have to say. I wish to ask him some questions.” - -Eurynome brought the seat at once and set a fleece upon it, and as soon -as Ulysses had sat down Penelope began by saying, “Stranger, I shall -first ask you who and whence are you? Tell me of your town and -parents.” - -“Madam,” answered Ulysses, “who on the face of the whole earth can dare -to chide with you? Your fame reaches the firmament of heaven itself; -you are like some blameless king, who upholds righteousness, as the -monarch over a great and valiant nation: the earth yields its wheat and -barley, the trees are loaded with fruit, the ewes bring forth lambs, -and the sea abounds with fish by reason of his virtues, and his people -do good deeds under him. Nevertheless, as I sit here in your house, ask -me some other question and do not seek to know my race and family, or -you will recall memories that will yet more increase my sorrow. I am -full of heaviness, but I ought not to sit weeping and wailing in -another person’s house, nor is it well to be thus grieving continually. -I shall have one of the servants or even yourself complaining of me, -and saying that my eyes swim with tears because I am heavy with wine.” - -Then Penelope answered, “Stranger, heaven robbed me of all beauty, -whether of face or figure, when the Argives set sail for Troy and my -dear husband with them. If he were to return and look after my affairs -I should be both more respected and should show a better presence to -the world. As it is, I am oppressed with care, and with the afflictions -which heaven has seen fit to heap upon me. The chiefs from all our -islands—Dulichium, Same, and Zacynthus, as also from Ithaca itself, are -wooing me against my will and are wasting my estate. I can therefore -show no attention to strangers, nor suppliants, nor to people who say -that they are skilled artisans, but am all the time broken-hearted -about Ulysses. They want me to marry again at once, and I have to -invent stratagems in order to deceive them. In the first place heaven -put it in my mind to set up a great tambour-frame in my room, and to -begin working upon an enormous piece of fine needlework. Then I said to -them, ‘Sweethearts, Ulysses is indeed dead, still, do not press me to -marry again immediately; wait—for I would not have my skill in -needlework perish unrecorded—till I have finished making a pall for the -hero Laertes, to be ready against the time when death shall take him. -He is very rich, and the women of the place will talk if he is laid out -without a pall.’ This was what I said, and they assented; whereon I -used to keep working at my great web all day long, but at night I would -unpick the stitches again by torch light. I fooled them in this way for -three years without their finding it out, but as time wore on and I was -now in my fourth year, in the waning of moons, and many days had been -accomplished, those good for nothing hussies my maids betrayed me to -the suitors, who broke in upon me and caught me; they were very angry -with me, so I was forced to finish my work whether I would or no. And -now I do not see how I can find any further shift for getting out of -this marriage. My parents are putting great pressure upon me, and my -son chafes at the ravages the suitors are making upon his estate, for -he is now old enough to understand all about it and is perfectly able -to look after his own affairs, for heaven has blessed him with an -excellent disposition. Still, notwithstanding all this, tell me who you -are and where you come from—for you must have had father and mother of -some sort; you cannot be the son of an oak or of a rock.” - -Then Ulysses answered, “Madam, wife of Ulysses, since you persist in -asking me about my family, I will answer, no matter what it costs me: -people must expect to be pained when they have been exiles as long as I -have, and suffered as much among as many peoples. Nevertheless, as -regards your question I will tell you all you ask. There is a fair and -fruitful island in mid-ocean called Crete; it is thickly peopled and -there are ninety cities in it: the people speak many different -languages which overlap one another, for there are Achaeans, brave -Eteocretans, Dorians of three-fold race, and noble Pelasgi. There is a -great town there, Cnossus, where Minos reigned who every nine years had -a conference with Jove himself.152 Minos was father to Deucalion, whose -son I am, for Deucalion had two sons Idomeneus and myself. Idomeneus -sailed for Troy, and I, who am the younger, am called Aethon; my -brother, however, was at once the older and the more valiant of the -two; hence it was in Crete that I saw Ulysses and showed him -hospitality, for the winds took him there as he was on his way to Troy, -carrying him out of his course from cape Malea and leaving him in -Amnisus off the cave of Ilithuia, where the harbours are difficult to -enter and he could hardly find shelter from the winds that were then -raging. As soon as he got there he went into the town and asked for -Idomeneus, claiming to be his old and valued friend, but Idomeneus had -already set sail for Troy some ten or twelve days earlier, so I took -him to my own house and showed him every kind of hospitality, for I had -abundance of everything. Moreover, I fed the men who were with him with -barley meal from the public store, and got subscriptions of wine and -oxen for them to sacrifice to their heart’s content. They stayed with -me twelve days, for there was a gale blowing from the North so strong -that one could hardly keep one’s feet on land. I suppose some -unfriendly god had raised it for them, but on the thirteenth day the -wind dropped, and they got away.” - -Many a plausible tale did Ulysses further tell her, and Penelope wept -as she listened, for her heart was melted. As the snow wastes upon the -mountain tops when the winds from South East and West have breathed -upon it and thawed it till the rivers run bank full with water, even so -did her cheeks overflow with tears for the husband who was all the time -sitting by her side. Ulysses felt for her and was sorry for her, but he -kept his eyes as hard as horn or iron without letting them so much as -quiver, so cunningly did he restrain his tears. Then, when she had -relieved herself by weeping, she turned to him again and said: “Now, -stranger, I shall put you to the test and see whether or no you really -did entertain my husband and his men, as you say you did. Tell me, -then, how he was dressed, what kind of a man he was to look at, and so -also with his companions.” - -“Madam,” answered Ulysses, “it is such a long time ago that I can -hardly say. Twenty years are come and gone since he left my home, and -went elsewhither; but I will tell you as well as I can recollect. -Ulysses wore a mantle of purple wool, double lined, and it was fastened -by a gold brooch with two catches for the pin. On the face of this -there was a device that shewed a dog holding a spotted fawn between his -fore paws, and watching it as it lay panting upon the ground. Every one -marvelled at the way in which these things had been done in gold, the -dog looking at the fawn, and strangling it, while the fawn was -struggling convulsively to escape.153 As for the shirt that he wore -next his skin, it was so soft that it fitted him like the skin of an -onion, and glistened in the sunlight to the admiration of all the women -who beheld it. Furthermore I say, and lay my saying to your heart, that -I do not know whether Ulysses wore these clothes when he left home, or -whether one of his companions had given them to him while he was on his -voyage; or possibly some one at whose house he was staying made him a -present of them, for he was a man of many friends and had few equals -among the Achaeans. I myself gave him a sword of bronze and a beautiful -purple mantle, double lined, with a shirt that went down to his feet, -and I sent him on board his ship with every mark of honour. He had a -servant with him, a little older than himself, and I can tell you what -he was like; his shoulders were hunched,154 he was dark, and he had -thick curly hair. His name was Eurybates, and Ulysses treated him with -greater familiarity than he did any of the others, as being the most -like-minded with himself.” - -Penelope was moved still more deeply as she heard the indisputable -proofs that Ulysses laid before her; and when she had again found -relief in tears she said to him, “Stranger, I was already disposed to -pity you, but henceforth you shall be honoured and made welcome in my -house. It was I who gave Ulysses the clothes you speak of. I took them -out of the store room and folded them up myself, and I gave him also -the gold brooch to wear as an ornament. Alas! I shall never welcome him -home again. It was by an ill fate that he ever set out for that -detested city whose very name I cannot bring myself even to mention.” - -Then Ulysses answered, “Madam, wife of Ulysses, do not disfigure -yourself further by grieving thus bitterly for your loss, though I can -hardly blame you for doing so. A woman who has loved her husband and -borne him children, would naturally be grieved at losing him, even -though he were a worse man than Ulysses, who they say was like a god. -Still, cease your tears and listen to what I can tell you. I will hide -nothing from you, and can say with perfect truth that I have lately -heard of Ulysses as being alive and on his way home; he is among the -Thesprotians, and is bringing back much valuable treasure that he has -begged from one and another of them; but his ship and all his crew were -lost as they were leaving the Thrinacian island, for Jove and the -sun-god were angry with him because his men had slaughtered the -sun-god’s cattle, and they were all drowned to a man. But Ulysses stuck -to the keel of the ship and was drifted on to the land of the -Phaeacians, who are near of kin to the immortals, and who treated him -as though he had been a god, giving him many presents, and wishing to -escort him home safe and sound. In fact Ulysses would have been here -long ago, had he not thought better to go from land to land gathering -wealth; for there is no man living who is so wily as he is; there is no -one can compare with him. Pheidon king of the Thesprotians told me all -this, and he swore to me—making drink-offerings in his house as he did -so—that the ship was by the water side and the crew found who would -take Ulysses to his own country. He sent me off first, for there -happened to be a Thesprotian ship sailing for the wheat-growing island -of Dulichium, but he showed me all the treasure Ulysses had got -together, and he had enough lying in the house of king Pheidon to keep -his family for ten generations; but the king said Ulysses had gone to -Dodona that he might learn Jove’s mind from the high oak tree, and know -whether after so long an absence he should return to Ithaca openly or -in secret. So you may know he is safe and will be here shortly; he is -close at hand and cannot remain away from home much longer; -nevertheless I will confirm my words with an oath, and call Jove who is -the first and mightiest of all gods to witness, as also that hearth of -Ulysses to which I have now come, that all I have spoken shall surely -come to pass. Ulysses will return in this self same year; with the end -of this moon and the beginning of the next he will be here.” - -“May it be even so,” answered Penelope; “if your words come true you -shall have such gifts and such good will from me that all who see you -shall congratulate you; but I know very well how it will be. Ulysses -will not return, neither will you get your escort hence, for so surely -as that Ulysses ever was, there are now no longer any such masters in -the house as he was, to receive honourable strangers or to further them -on their way home. And now, you maids, wash his feet for him, and make -him a bed on a couch with rugs and blankets, that he may be warm and -quiet till morning. Then, at day break wash him and anoint him again, -that he may sit in the cloister and take his meals with Telemachus. It -shall be the worse for any one of these hateful people who is uncivil -to him; like it or not, he shall have no more to do in this house. For -how, sir, shall you be able to learn whether or no I am superior to -others of my sex both in goodness of heart and understanding, if I let -you dine in my cloisters squalid and ill clad? Men live but for a -little season; if they are hard, and deal hardly, people wish them ill -so long as they are alive, and speak contemptuously of them when they -are dead, but he that is righteous and deals righteously, the people -tell of his praise among all lands, and many shall call him blessed.” - -Ulysses answered, “Madam, I have foresworn rugs and blankets from the -day that I left the snowy ranges of Crete to go on shipboard. I will -lie as I have lain on many a sleepless night hitherto. Night after -night have I passed in any rough sleeping place, and waited for -morning. Nor, again, do I like having my feet washed; I shall not let -any of the young hussies about your house touch my feet; but, if you -have any old and respectable woman who has gone through as much trouble -as I have, I will allow her to wash them.” - -To this Penelope said, “My dear sir, of all the guests who ever yet -came to my house there never was one who spoke in all things with such -admirable propriety as you do. There happens to be in the house a most -respectable old woman—the same who received my poor dear husband in her -arms the night he was born, and nursed him in infancy. She is very -feeble now, but she shall wash your feet.” “Come here,” said she, -“Euryclea, and wash your master’s age-mate; I suppose Ulysses’ hands -and feet are very much the same now as his are, for trouble ages all of -us dreadfully fast.” - -On these words the old woman covered her face with her hands; she began -to weep and made lamentation saying, “My dear child, I cannot think -whatever I am to do with you. I am certain no one was ever more -god-fearing than yourself, and yet Jove hates you. No one in the whole -world ever burned him more thigh bones, nor gave him finer hecatombs -when you prayed you might come to a green old age yourself and see your -son grow up to take after you: yet see how he has prevented you alone -from ever getting back to your own home. I have no doubt the women in -some foreign palace which Ulysses has got to are gibing at him as all -these sluts here have been gibing at you. I do not wonder at your not -choosing to let them wash you after the manner in which they have -insulted you; I will wash your feet myself gladly enough, as Penelope -has said that I am to do so; I will wash them both for Penelope’s sake -and for your own, for you have raised the most lively feelings of -compassion in my mind; and let me say this moreover, which pray attend -to; we have had all kinds of strangers in distress come here before -now, but I make bold to say that no one ever yet came who was so like -Ulysses in figure, voice, and feet as you are.” - -“Those who have seen us both,” answered Ulysses, “have always said we -were wonderfully like each other, and now you have noticed it too.” - -Then the old woman took the cauldron in which she was going to wash his -feet, and poured plenty of cold water into it, adding hot till the bath -was warm enough. Ulysses sat by the fire, but ere long he turned away -from the light, for it occurred to him that when the old woman had hold -of his leg she would recognise a certain scar which it bore, whereon -the whole truth would come out. And indeed as soon as she began washing -her master, she at once knew the scar as one that had been given him by -a wild boar when he was hunting on Mt. Parnassus with his excellent -grandfather Autolycus—who was the most accomplished thief and perjurer -in the whole world—and with the sons of Autolycus. Mercury himself had -endowed him with this gift, for he used to burn the thigh bones of -goats and kids to him, so he took pleasure in his companionship. It -happened once that Autolycus had gone to Ithaca and had found the child -of his daughter just born. As soon as he had done supper Euryclea set -the infant upon his knees and said, “Autolycus, you must find a name -for your grandson; you greatly wished that you might have one.” - -“Son-in-law and daughter,” replied Autolycus, “call the child thus: I -am highly displeased with a large number of people in one place and -another, both men and women; so name the child ‘Ulysses,’ or the child -of anger. When he grows up and comes to visit his mother’s family on -Mt. Parnassus, where my possessions lie, I will make him a present and -will send him on his way rejoicing.” - -Ulysses, therefore, went to Parnassus to get the presents from -Autolycus, who with his sons shook hands with him and gave him welcome. -His grandmother Amphithea threw her arms about him, and kissed his -head, and both his beautiful eyes, while Autolycus desired his sons to -get dinner ready, and they did as he told them. They brought in a five -year old bull, flayed it, made it ready and divided it into joints; -these they then cut carefully up into smaller pieces and spitted them; -they roasted them sufficiently and served the portions round. Thus -through the livelong day to the going down of the sun they feasted, and -every man had his full share so that all were satisfied; but when the -sun set and it came on dark, they went to bed and enjoyed the boon of -sleep. - -When the child of morning, rosy-fingered Dawn, appeared, the sons of -Autolycus went out with their hounds hunting, and Ulysses went too. -They climbed the wooded slopes of Parnassus and soon reached its breezy -upland valleys; but as the sun was beginning to beat upon the fields, -fresh-risen from the slow still currents of Oceanus, they came to a -mountain dell. The dogs were in front searching for the tracks of the -beast they were chasing, and after them came the sons of Autolycus, -among whom was Ulysses, close behind the dogs, and he had a long spear -in his hand. Here was the lair of a huge boar among some thick -brushwood, so dense that the wind and rain could not get through it, -nor could the sun’s rays pierce it, and the ground underneath lay thick -with fallen leaves. The boar heard the noise of the men’s feet, and the -hounds baying on every side as the huntsmen came up to him, so he -rushed from his lair, raised the bristles on his neck, and stood at bay -with fire flashing from his eyes. Ulysses was the first to raise his -spear and try to drive it into the brute, but the boar was too quick -for him, and charged him sideways, ripping him above the knee with a -gash that tore deep though it did not reach the bone. As for the boar, -Ulysses hit him on the right shoulder, and the point of the spear went -right through him, so that he fell groaning in the dust until the life -went out of him. The sons of Autolycus busied themselves with the -carcass of the boar, and bound Ulysses’ wound; then, after saying a -spell to stop the bleeding, they went home as fast as they could. But -when Autolycus and his sons had thoroughly healed Ulysses, they made -him some splendid presents, and sent him back to Ithaca with much -mutual good will. When he got back, his father and mother were rejoiced -to see him, and asked him all about it, and how he had hurt himself to -get the scar; so he told them how the boar had ripped him when he was -out hunting with Autolycus and his sons on Mt. Parnassus. - -As soon as Euryclea had got the scarred limb in her hands and had well -hold of it, she recognised it and dropped the foot at once. The leg -fell into the bath, which rang out and was overturned, so that all the -water was spilt on the ground; Euryclea’s eyes between her joy and her -grief filled with tears, and she could not speak, but she caught -Ulysses by the beard and said, “My dear child, I am sure you must be -Ulysses himself, only I did not know you till I had actually touched -and handled you.” - -As she spoke she looked towards Penelope, as though wanting to tell her -that her dear husband was in the house, but Penelope was unable to look -in that direction and observe what was going on, for Minerva had -diverted her attention; so Ulysses caught Euryclea by the throat with -his right hand and with his left drew her close to him, and said, -“Nurse, do you wish to be the ruin of me, you who nursed me at your own -breast, now that after twenty years of wandering I am at last come to -my own home again? Since it has been borne in upon you by heaven to -recognise me, hold your tongue, and do not say a word about it to any -one else in the house, for if you do I tell you—and it shall surely -be—that if heaven grants me to take the lives of these suitors, I will -not spare you, though you are my own nurse, when I am killing the other -women.” - -“My child,” answered Euryclea, “what are you talking about? You know -very well that nothing can either bend or break me. I will hold my -tongue like a stone or a piece of iron; furthermore let me say, and lay -my saying to your heart, when heaven has delivered the suitors into -your hand, I will give you a list of the women in the house who have -been ill-behaved, and of those who are guiltless.” - -And Ulysses answered, “Nurse, you ought not to speak in that way; I am -well able to form my own opinion about one and all of them; hold your -tongue and leave everything to heaven.” - -As he said this Euryclea left the cloister to fetch some more water, -for the first had been all spilt; and when she had washed him and -anointed him with oil, Ulysses drew his seat nearer to the fire to warm -himself, and hid the scar under his rags. Then Penelope began talking -to him and said: - -“Stranger, I should like to speak with you briefly about another -matter. It is indeed nearly bed time—for those, at least, who can sleep -in spite of sorrow. As for myself, heaven has given me a life of such -unmeasurable woe, that even by day when I am attending to my duties and -looking after the servants, I am still weeping and lamenting during the -whole time; then, when night comes, and we all of us go to bed, I lie -awake thinking, and my heart becomes a prey to the most incessant and -cruel tortures. As the dun nightingale, daughter of Pandareus, sings in -the early spring from her seat in shadiest covert hid, and with many a -plaintive trill pours out the tale how by mishap she killed her own -child Itylus, son of king Zethus, even so does my mind toss and turn in -its uncertainty whether I ought to stay with my son here, and safeguard -my substance, my bondsmen, and the greatness of my house, out of regard -to public opinion and the memory of my late husband, or whether it is -not now time for me to go with the best of these suitors who are wooing -me and making me such magnificent presents. As long as my son was still -young, and unable to understand, he would not hear of my leaving my -husband’s house, but now that he is full grown he begs and prays me to -do so, being incensed at the way in which the suitors are eating up his -property. Listen, then, to a dream that I have had and interpret it for -me if you can. I have twenty geese about the house that eat mash out of -a trough,155 and of which I am exceedingly fond. I dreamed that a great -eagle came swooping down from a mountain, and dug his curved beak into -the neck of each of them till he had killed them all. Presently he -soared off into the sky, and left them lying dead about the yard; -whereon I wept in my dream till all my maids gathered round me, so -piteously was I grieving because the eagle had killed my geese. Then he -came back again, and perching on a projecting rafter spoke to me with -human voice, and told me to leave off crying. ‘Be of good courage,’ he -said, ‘daughter of Icarius; this is no dream, but a vision of good omen -that shall surely come to pass. The geese are the suitors, and I am no -longer an eagle, but your own husband, who am come back to you, and who -will bring these suitors to a disgraceful end.’ On this I woke, and -when I looked out I saw my geese at the trough eating their mash as -usual.” - -“This dream, Madam,” replied Ulysses, “can admit but of one -interpretation, for had not Ulysses himself told you how it shall be -fulfilled? The death of the suitors is portended, and not one single -one of them will escape.” - -And Penelope answered, “Stranger, dreams are very curious and -unaccountable things, and they do not by any means invariably come -true. There are two gates through which these unsubstantial fancies -proceed; the one is of horn, and the other ivory. Those that come -through the gate of ivory are fatuous, but those from the gate of horn -mean something to those that see them. I do not think, however, that my -own dream came through the gate of horn, though I and my son should be -most thankful if it proves to have done so. Furthermore I say—and lay -my saying to your heart—the coming dawn will usher in the ill-omened -day that is to sever me from the house of Ulysses, for I am about to -hold a tournament of axes. My husband used to set up twelve axes in the -court, one in front of the other, like the stays upon which a ship is -built; he would then go back from them and shoot an arrow through the -whole twelve. I shall make the suitors try to do the same thing, and -whichever of them can string the bow most easily, and send his arrow -through all the twelve axes, him will I follow, and quit this house of -my lawful husband, so goodly and so abounding in wealth. But even so, I -doubt not that I shall remember it in my dreams.” - -Then Ulysses answered, “Madam, wife of Ulysses, you need not defer your -tournament, for Ulysses will return ere ever they can string the bow, -handle it how they will, and send their arrows through the iron.” - -To this Penelope said, “As long, sir, as you will sit here and talk to -me, I can have no desire to go to bed. Still, people cannot do -permanently without sleep, and heaven has appointed us dwellers on -earth a time for all things. I will therefore go upstairs and recline -upon that couch which I have never ceased to flood with my tears from -the day Ulysses set out for the city with a hateful name.” - -She then went upstairs to her own room, not alone, but attended by her -maidens, and when there, she lamented her dear husband till Minerva -shed sweet sleep over her eyelids. - - - - -BOOK XX - - -ULYSSES CANNOT SLEEP—PENELOPE’S PRAYER TO DIANA—THE TWO SIGNS FROM -HEAVEN—EUMAEUS AND PHILOETIUS ARRIVE—THE SUITORS DINE—CTESIPPUS THROWS -AN OX’S FOOT AT ULYSSES—THEOCLYMENUS FORETELLS DISASTER AND LEAVES THE -HOUSE. - - -Ulysses slept in the cloister upon an undressed bullock’s hide, on the -top of which he threw several skins of the sheep the suitors had eaten, -and Eurynome156 threw a cloak over him after he had laid himself down. -There, then, Ulysses lay wakefully brooding upon the way in which he -should kill the suitors; and by and by, the women who had been in the -habit of misconducting themselves with them, left the house giggling -and laughing with one another. This made Ulysses very angry, and he -doubted whether to get up and kill every single one of them then and -there, or to let them sleep one more and last time with the suitors. -His heart growled within him, and as a bitch with puppies growls and -shows her teeth when she sees a stranger, so did his heart growl with -anger at the evil deeds that were being done: but he beat his breast -and said, “Heart, be still, you had worse than this to bear on the day -when the terrible Cyclops ate your brave companions; yet you bore it in -silence till your cunning got you safe out of the cave, though you made -sure of being killed.” - -Thus he chided with his heart, and checked it into endurance, but he -tossed about as one who turns a paunch full of blood and fat in front -of a hot fire, doing it first on one side and then on the other, that -he may get it cooked as soon as possible, even so did he turn himself -about from side to side, thinking all the time how, single handed as he -was, he should contrive to kill so large a body of men as the wicked -suitors. But by and by Minerva came down from heaven in the likeness of -a woman, and hovered over his head saying, “My poor unhappy man, why do -you lie awake in this way? This is your house: your wife is safe inside -it, and so is your son who is just such a young man as any father may -be proud of.” - -“Goddess,” answered Ulysses, “all that you have said is true, but I am -in some doubt as to how I shall be able to kill these wicked suitors -single handed, seeing what a number of them there always are. And there -is this further difficulty, which is still more considerable. Supposing -that with Jove’s and your assistance I succeed in killing them, I must -ask you to consider where I am to escape to from their avengers when it -is all over.” - -“For shame,” replied Minerva, “why, any one else would trust a worse -ally than myself, even though that ally were only a mortal and less -wise than I am. Am I not a goddess, and have I not protected you -throughout in all your troubles? I tell you plainly that even though -there were fifty bands of men surrounding us and eager to kill us, you -should take all their sheep and cattle, and drive them away with you. -But go to sleep; it is a very bad thing to lie awake all night, and you -shall be out of your troubles before long.” - -As she spoke she shed sleep over his eyes, and then went back to -Olympus. - -While Ulysses was thus yielding himself to a very deep slumber that -eased the burden of his sorrows, his admirable wife awoke, and sitting -up in her bed began to cry. When she had relieved herself by weeping -she prayed to Diana saying, “Great Goddess Diana, daughter of Jove, -drive an arrow into my heart and slay me; or let some whirlwind snatch -me up and bear me through paths of darkness till it drop me into the -mouths of over-flowing Oceanus, as it did the daughters of Pandareus. -The daughters of Pandareus lost their father and mother, for the gods -killed them, so they were left orphans. But Venus took care of them, -and fed them on cheese, honey, and sweet wine. Juno taught them to -excel all women in beauty of form and understanding; Diana gave them an -imposing presence, and Minerva endowed them with every kind of -accomplishment; but one day when Venus had gone up to Olympus to see -Jove about getting them married (for well does he know both what shall -happen and what not happen to every one) the storm winds came and -spirited them away to become handmaids to the dread Erinyes. Even so I -wish that the gods who live in heaven would hide me from mortal sight, -or that fair Diana might strike me, for I would fain go even beneath -the sad earth if I might do so still looking towards Ulysses only, and -without having to yield myself to a worse man than he was. Besides, no -matter how much people may grieve by day, they can put up with it so -long as they can sleep at night, for when the eyes are closed in -slumber people forget good and ill alike; whereas my misery haunts me -even in my dreams. This very night methought there was one lying by my -side who was like Ulysses as he was when he went away with his host, -and I rejoiced, for I believed that it was no dream, but the very truth -itself.” - -On this the day broke, but Ulysses heard the sound of her weeping, and -it puzzled him, for it seemed as though she already knew him and was by -his side. Then he gathered up the cloak and the fleeces on which he had -lain, and set them on a seat in the cloister, but he took the bullock’s -hide out into the open. He lifted up his hands to heaven, and prayed, -saying “Father Jove, since you have seen fit to bring me over land and -sea to my own home after all the afflictions you have laid upon me, -give me a sign out of the mouth of some one or other of those who are -now waking within the house, and let me have another sign of some kind -from outside.” - -Thus did he pray. Jove heard his prayer and forthwith thundered high up -among the clouds from the splendour of Olympus, and Ulysses was glad -when he heard it. At the same time within the house, a miller-woman -from hard by in the mill room lifted up her voice and gave him another -sign. There were twelve miller-women whose business it was to grind -wheat and barley which are the staff of life. The others had ground -their task and had gone to take their rest, but this one had not yet -finished, for she was not so strong as they were, and when she heard -the thunder she stopped grinding and gave the sign to her master. -“Father Jove,” said she, “you, who rule over heaven and earth, you have -thundered from a clear sky without so much as a cloud in it, and this -means something for somebody; grant the prayer, then, of me your poor -servant who calls upon you, and let this be the very last day that the -suitors dine in the house of Ulysses. They have worn me out with labour -of grinding meal for them, and I hope they may never have another -dinner anywhere at all.” - -Ulysses was glad when he heard the omens conveyed to him by the woman’s -speech, and by the thunder, for he knew they meant that he should -avenge himself on the suitors. - -Then the other maids in the house rose and lit the fire on the hearth; -Telemachus also rose and put on his clothes. He girded his sword about -his shoulder, bound his sandals on to his comely feet, and took a -doughty spear with a point of sharpened bronze; then he went to the -threshold of the cloister and said to Euryclea, “Nurse, did you make -the stranger comfortable both as regards bed and board, or did you let -him shift for himself?—for my mother, good woman though she is, has a -way of paying great attention to second-rate people, and of neglecting -others who are in reality much better men.” - -“Do not find fault child,” said Euryclea, “when there is no one to find -fault with. The stranger sat and drank his wine as long as he liked: -your mother did ask him if he would take any more bread and he said he -would not. When he wanted to go to bed she told the servants to make -one for him, but he said he was such a wretched outcast that he would -not sleep on a bed and under blankets; he insisted on having an -undressed bullock’s hide and some sheepskins put for him in the -cloister and I threw a cloak over him myself.”157 - -Then Telemachus went out of the court to the place where the Achaeans -were meeting in assembly; he had his spear in his hand, and he was not -alone, for his two dogs went with him. But Euryclea called the maids -and said, “Come, wake up; set about sweeping the cloisters and -sprinkling them with water to lay the dust; put the covers on the -seats; wipe down the tables, some of you, with a wet sponge; clean out -the mixing-jugs and the cups, and go for water from the fountain at -once; the suitors will be here directly; they will be here early, for -it is a feast day.” - -Thus did she speak, and they did even as she had said: twenty of them -went to the fountain for water, and the others set themselves busily to -work about the house. The men who were in attendance on the suitors -also came up and began chopping firewood. By and by the women returned -from the fountain, and the swineherd came after them with the three -best pigs he could pick out. These he let feed about the premises, and -then he said good-humouredly to Ulysses, “Stranger, are the suitors -treating you any better now, or are they as insolent as ever?” - -“May heaven,” answered Ulysses, “requite to them the wickedness with -which they deal high-handedly in another man’s house without any sense -of shame.” - -Thus did they converse; meanwhile Melanthius the goatherd came up, for -he too was bringing in his best goats for the suitors’ dinner; and he -had two shepherds with him. They tied the goats up under the gatehouse, -and then Melanthius began gibing at Ulysses. “Are you still here, -stranger,” said he, “to pester people by begging about the house? Why -can you not go elsewhere? You and I shall not come to an understanding -before we have given each other a taste of our fists. You beg without -any sense of decency: are there not feasts elsewhere among the -Achaeans, as well as here?” - -Ulysses made no answer, but bowed his head and brooded. Then a third -man, Philoetius, joined them, who was bringing in a barren heifer and -some goats. These were brought over by the boatmen who are there to -take people over when any one comes to them. So Philoetius made his -heifer and his goats secure under the gatehouse, and then went up to -the swineherd. “Who, Swineherd,” said he, “is this stranger that is -lately come here? Is he one of your men? What is his family? Where does -he come from? Poor fellow, he looks as if he had been some great man, -but the gods give sorrow to whom they will—even to kings if it so -pleases them.” - -As he spoke he went up to Ulysses and saluted him with his right hand; -“Good day to you, father stranger,” said he, “you seem to be very -poorly off now, but I hope you will have better times by and by. Father -Jove, of all gods you are the most malicious. We are your own children, -yet you show us no mercy in all our misery and afflictions. A sweat -came over me when I saw this man, and my eyes filled with tears, for he -reminds me of Ulysses, who I fear is going about in just such rags as -this man’s are, if indeed he is still among the living. If he is -already dead and in the house of Hades, then, alas! for my good master, -who made me his stockman when I was quite young among the -Cephallenians, and now his cattle are countless; no one could have done -better with them than I have, for they have bred like ears of corn; -nevertheless I have to keep bringing them in for others to eat, who -take no heed to his son though he is in the house, and fear not the -wrath of heaven, but are already eager to divide Ulysses’ property -among them because he has been away so long. I have often thought—only -it would not be right while his son is living—of going off with the -cattle to some foreign country; bad as this would be, it is still -harder to stay here and be ill-treated about other people’s herds. My -position is intolerable, and I should long since have run away and put -myself under the protection of some other chief, only that I believe my -poor master will yet return, and send all these suitors flying out of -the house.” - -“Stockman,” answered Ulysses, “you seem to be a very well-disposed -person, and I can see that you are a man of sense. Therefore I will -tell you, and will confirm my words with an oath. By Jove, the chief of -all gods, and by that hearth of Ulysses to which I am now come, Ulysses -shall return before you leave this place, and if you are so minded you -shall see him killing the suitors who are now masters here.” - -“If Jove were to bring this to pass,” replied the stockman, “you should -see how I would do my very utmost to help him.” - -And in like manner Eumaeus prayed that Ulysses might return home. - -Thus did they converse. Meanwhile the suitors were hatching a plot to -murder Telemachus: but a bird flew near them on their left hand—an -eagle with a dove in its talons. On this Amphinomus said, “My friends, -this plot of ours to murder Telemachus will not succeed; let us go to -dinner instead.” - -The others assented, so they went inside and laid their cloaks on the -benches and seats. They sacrificed the sheep, goats, pigs, and the -heifer, and when the inward meats were cooked they served them round. -They mixed the wine in the mixing-bowls, and the swineherd gave every -man his cup, while Philoetius handed round the bread in the bread -baskets, and Melanthius poured them out their wine. Then they laid -their hands upon the good things that were before them. - -Telemachus purposely made Ulysses sit in the part of the cloister that -was paved with stone;158 he gave him a shabby looking seat at a little -table to himself, and had his portion of the inward meats brought to -him, with his wine in a gold cup. “Sit there,” said he, “and drink your -wine among the great people. I will put a stop to the gibes and blows -of the suitors, for this is no public house, but belongs to Ulysses, -and has passed from him to me. Therefore, suitors, keep your hands and -your tongues to yourselves, or there will be mischief.” - -The suitors bit their lips, and marvelled at the boldness of his -speech; then Antinous said, “We do not like such language but we will -put up with it, for Telemachus is threatening us in good earnest. If -Jove had let us we should have put a stop to his brave talk ere now.” - -Thus spoke Antinous, but Telemachus heeded him not. Meanwhile the -heralds were bringing the holy hecatomb through the city, and the -Achaeans gathered under the shady grove of Apollo. - -Then they roasted the outer meat, drew it off the spits, gave every man -his portion, and feasted to their heart’s content; those who waited at -table gave Ulysses exactly the same portion as the others had, for -Telemachus had told them to do so. - -But Minerva would not let the suitors for one moment drop their -insolence, for she wanted Ulysses to become still more bitter against -them. Now there happened to be among them a ribald fellow, whose name -was Ctesippus, and who came from Same. This man, confident in his great -wealth, was paying court to the wife of Ulysses, and said to the -suitors, “Hear what I have to say. The stranger has already had as -large a portion as any one else; this is well, for it is not right nor -reasonable to ill-treat any guest of Telemachus who comes here. I will, -however, make him a present on my own account, that he may have -something to give to the bath-woman, or to some other of Ulysses’ -servants.” - -As he spoke he picked up a heifer’s foot from the meat-basket in which -it lay, and threw it at Ulysses, but Ulysses turned his head a little -aside, and avoided it, smiling grimly Sardinian fashion159 as he did -so, and it hit the wall, not him. On this Telemachus spoke fiercely to -Ctesippus, “It is a good thing for you,” said he, “that the stranger -turned his head so that you missed him. If you had hit him I should -have run you through with my spear, and your father would have had to -see about getting you buried rather than married in this house. So let -me have no more unseemly behaviour from any of you, for I am grown up -now to the knowledge of good and evil and understand what is going on, -instead of being the child that I have been heretofore. I have long -seen you killing my sheep and making free with my corn and wine: I have -put up with this, for one man is no match for many, but do me no -further violence. Still, if you wish to kill me, kill me; I would far -rather die than see such disgraceful scenes day after day—guests -insulted, and men dragging the women servants about the house in an -unseemly way.” - -They all held their peace till at last Agelaus son of Damastor said, -“No one should take offence at what has just been said, nor gainsay it, -for it is quite reasonable. Leave off, therefore, ill-treating the -stranger, or any one else of the servants who are about the house; I -would say, however, a friendly word to Telemachus and his mother, which -I trust may commend itself to both. ‘As long,’ I would say, ‘as you had -ground for hoping that Ulysses would one day come home, no one could -complain of your waiting and suffering160 the suitors to be in your -house. It would have been better that he should have returned, but it -is now sufficiently clear that he will never do so; therefore talk all -this quietly over with your mother, and tell her to marry the best man, -and the one who makes her the most advantageous offer. Thus you will -yourself be able to manage your own inheritance, and to eat and drink -in peace, while your mother will look after some other man’s house, not -yours.’” - -To this Telemachus answered, “By Jove, Agelaus, and by the sorrows of -my unhappy father, who has either perished far from Ithaca, or is -wandering in some distant land, I throw no obstacles in the way of my -mother’s marriage; on the contrary I urge her to choose whomsoever she -will, and I will give her numberless gifts into the bargain, but I dare -not insist point blank that she shall leave the house against her own -wishes. Heaven forbid that I should do this.” - -Minerva now made the suitors fall to laughing immoderately, and set -their wits wandering; but they were laughing with a forced laughter. -Their meat became smeared with blood; their eyes filled with tears, and -their hearts were heavy with forebodings. Theoclymenus saw this and -said, “Unhappy men, what is it that ails you? There is a shroud of -darkness drawn over you from head to foot, your cheeks are wet with -tears; the air is alive with wailing voices; the walls and roof-beams -drip blood; the gate of the cloisters and the court beyond them are -full of ghosts trooping down into the night of hell; the sun is blotted -out of heaven, and a blighting gloom is over all the land.” - -Thus did he speak, and they all of them laughed heartily. Eurymachus -then said, “This stranger who has lately come here has lost his senses. -Servants, turn him out into the streets, since he finds it so dark -here.” - -But Theoclymenus said, “Eurymachus, you need not send any one with me. -I have eyes, ears, and a pair of feet of my own, to say nothing of an -understanding mind. I will take these out of the house with me, for I -see mischief overhanging you, from which not one of you men who are -insulting people and plotting ill deeds in the house of Ulysses will be -able to escape.” - -He left the house as he spoke, and went back to Piraeus who gave him -welcome, but the suitors kept looking at one another and provoking -Telemachus by laughing at the strangers. One insolent fellow said to -him, “Telemachus, you are not happy in your guests; first you have this -importunate tramp, who comes begging bread and wine and has no skill -for work or for hard fighting, but is perfectly useless, and now here -is another fellow who is setting himself up as a prophet. Let me -persuade you, for it will be much better to put them on board ship and -send them off to the Sicels to sell for what they will bring.” - -Telemachus gave him no heed, but sat silently watching his father, -expecting every moment that he would begin his attack upon the suitors. - -Meanwhile the daughter of Icarius, wise Penelope, had had a rich seat -placed for her facing the court and cloisters, so that she could hear -what every one was saying. The dinner indeed had been prepared amid -much merriment; it had been both good and abundant, for they had -sacrificed many victims; but the supper was yet to come, and nothing -can be conceived more gruesome than the meal which a goddess and a -brave man were soon to lay before them—for they had brought their doom -upon themselves. - - - - -BOOK XXI - - -THE TRIAL OF THE AXES, DURING WHICH ULYSSES REVEALS HIMSELF TO EUMAEUS -AND PHILOETIUS - - -Minerva now put it in Penelope’s mind to make the suitors try their -skill with the bow and with the iron axes, in contest among themselves, -as a means of bringing about their destruction. She went upstairs and -got the store-room key, which was made of bronze and had a handle of -ivory; she then went with her maidens into the store-room at the end of -the house, where her husband’s treasures of gold, bronze, and wrought -iron were kept, and where was also his bow, and the quiver full of -deadly arrows that had been given him by a friend whom he had met in -Lacedaemon—Iphitus the son of Eurytus. The two fell in with one another -in Messene at the house of Ortilochus, where Ulysses was staying in -order to recover a debt that was owing from the whole people; for the -Messenians had carried off three hundred sheep from Ithaca, and had -sailed away with them and with their shepherds. In quest of these -Ulysses took a long journey while still quite young, for his father and -the other chieftains sent him on a mission to recover them. Iphitus had -gone there also to try and get back twelve brood mares that he had -lost, and the mule foals that were running with them. These mares were -the death of him in the end, for when he went to the house of Jove’s -son, mighty Hercules, who performed such prodigies of valour, Hercules -to his shame killed him, though he was his guest, for he feared not -heaven’s vengeance, nor yet respected his own table which he had set -before Iphitus, but killed him in spite of everything, and kept the -mares himself. It was when claiming these that Iphitus met Ulysses, and -gave him the bow which mighty Eurytus had been used to carry, and which -on his death had been left by him to his son. Ulysses gave him in -return a sword and a spear, and this was the beginning of a fast -friendship, although they never visited at one another’s houses, for -Jove’s son Hercules killed Iphitus ere they could do so. This bow, -then, given him by Iphitus, had not been taken with him by Ulysses when -he sailed for Troy; he had used it so long as he had been at home, but -had left it behind as having been a keepsake from a valued friend. - -Penelope presently reached the oak threshold of the store-room; the -carpenter had planed this duly, and had drawn a line on it so as to get -it quite straight; he had then set the door posts into it and hung the -doors. She loosed the strap from the handle of the door, put in the -key, and drove it straight home to shoot back the bolts that held the -doors;161 these flew open with a noise like a bull bellowing in a -meadow, and Penelope stepped upon the raised platform, where the chests -stood in which the fair linen and clothes were laid by along with -fragrant herbs: reaching thence, she took down the bow with its bow -case from the peg on which it hung. She sat down with it on her knees, -weeping bitterly as she took the bow out of its case, and when her -tears had relieved her, she went to the cloister where the suitors -were, carrying the bow and the quiver, with the many deadly arrows that -were inside it. Along with her came her maidens, bearing a chest that -contained much iron and bronze which her husband had won as prizes. -When she reached the suitors, she stood by one of the bearing-posts -supporting the roof of the cloister, holding a veil before her face, -and with a maid on either side of her. Then she said: - -“Listen to me you suitors, who persist in abusing the hospitality of -this house because its owner has been long absent, and without other -pretext than that you want to marry me; this, then, being the prize -that you are contending for, I will bring out the mighty bow of -Ulysses, and whomsoever of you shall string it most easily and send his -arrow through each one of twelve axes, him will I follow and quit this -house of my lawful husband, so goodly, and so abounding in wealth. But -even so I doubt not that I shall remember it in my dreams.” - -As she spoke, she told Eumaeus to set the bow and the pieces of iron -before the suitors, and Eumaeus wept as he took them to do as she had -bidden him. Hard by, the stockman wept also when he saw his master’s -bow, but Antinous scolded them. “You country louts,” said he, “silly -simpletons; why should you add to the sorrows of your mistress by -crying in this way? She has enough to grieve her in the loss of her -husband; sit still, therefore, and eat your dinners in silence, or go -outside if you want to cry, and leave the bow behind you. We suitors -shall have to contend for it with might and main, for we shall find it -no light matter to string such a bow as this is. There is not a man of -us all who is such another as Ulysses; for I have seen him and remember -him, though I was then only a child.” - -This was what he said, but all the time he was expecting to be able to -string the bow and shoot through the iron, whereas in fact he was to be -the first that should taste of the arrows from the hands of Ulysses, -whom he was dishonouring in his own house—egging the others on to do so -also. - -Then Telemachus spoke. “Great heavens!” he exclaimed, “Jove must have -robbed me of my senses. Here is my dear and excellent mother saying she -will quit this house and marry again, yet I am laughing and enjoying -myself as though there were nothing happening. But, suitors, as the -contest has been agreed upon, let it go forward. It is for a woman -whose peer is not to be found in Pylos, Argos, or Mycene, nor yet in -Ithaca nor on the mainland. You know this as well as I do; what need -have I to speak in praise of my mother? Come on, then, make no excuses -for delay, but let us see whether you can string the bow or no. I too -will make trial of it, for if I can string it and shoot through the -iron, I shall not suffer my mother to quit this house with a stranger, -not if I can win the prizes which my father won before me.” - -As he spoke he sprang from his seat, threw his crimson cloak from him, -and took his sword from his shoulder. First he set the axes in a row, -in a long groove which he had dug for them, and had made straight by -line.162 Then he stamped the earth tight round them, and everyone was -surprised when they saw him set them up so orderly, though he had never -seen anything of the kind before. This done, he went on to the pavement -to make trial of the bow; thrice did he tug at it, trying with all his -might to draw the string, and thrice he had to leave off, though he had -hoped to string the bow and shoot through the iron. He was trying for -the fourth time, and would have strung it had not Ulysses made a sign -to check him in spite of all his eagerness. So he said: - -“Alas! I shall either be always feeble and of no prowess, or I am too -young, and have not yet reached my full strength so as to be able to -hold my own if any one attacks me. You others, therefore, who are -stronger than I, make trial of the bow and get this contest settled.” - -On this he put the bow down, letting it lean against the door [that led -into the house] with the arrow standing against the top of the bow. -Then he sat down on the seat from which he had risen, and Antinous -said: - -“Come on each of you in his turn, going towards the right from the -place at which the cupbearer begins when he is handing round the wine.” - -The rest agreed, and Leiodes son of Oenops was the first to rise. He -was sacrificial priest to the suitors, and sat in the corner near the -mixing-bowl. 163 He was the only man who hated their evil deeds and was -indignant with the others. He was now the first to take the bow and -arrow, so he went on to the pavement to make his trial, but he could -not string the bow, for his hands were weak and unused to hard work, -they therefore soon grew tired, and he said to the suitors, “My -friends, I cannot string it; let another have it, this bow shall take -the life and soul out of many a chief among us, for it is better to die -than to live after having missed the prize that we have so long striven -for, and which has brought us so long together. Some one of us is even -now hoping and praying that he may marry Penelope, but when he has seen -this bow and tried it, let him woo and make bridal offerings to some -other woman, and let Penelope marry whoever makes her the best offer -and whose lot it is to win her.” - -On this he put the bow down, letting it lean against the door,164 with -the arrow standing against the tip of the bow. Then he took his seat -again on the seat from which he had risen; and Antinous rebuked him -saying: - -“Leiodes, what are you talking about? Your words are monstrous and -intolerable; it makes me angry to listen to you. Shall, then, this bow -take the life of many a chief among us, merely because you cannot bend -it yourself? True, you were not born to be an archer, but there are -others who will soon string it.” - -Then he said to Melanthius the goatherd, “Look sharp, light a fire in -the court, and set a seat hard by with a sheep skin on it; bring us -also a large ball of lard, from what they have in the house. Let us -warm the bow and grease it—we will then make trial of it again, and -bring the contest to an end.” - -Melanthius lit the fire, and set a seat covered with sheep skins beside -it. He also brought a great ball of lard from what they had in the -house, and the suitors warmed the bow and again made trial of it, but -they were none of them nearly strong enough to string it. Nevertheless -there still remained Antinous and Eurymachus, who were the ringleaders -among the suitors and much the foremost among them all. - -Then the swineherd and the stockman left the cloisters together, and -Ulysses followed them. When they had got outside the gates and the -outer yard, Ulysses said to them quietly: - -“Stockman, and you swineherd, I have something in my mind which I am in -doubt whether to say or no; but I think I will say it. What manner of -men would you be to stand by Ulysses, if some god should bring him back -here all of a sudden? Say which you are disposed to do—to side with the -suitors, or with Ulysses?” - -“Father Jove,” answered the stockman, “would indeed that you might so -ordain it. If some god were but to bring Ulysses back, you should see -with what might and main I would fight for him.” - -In like words Eumaeus prayed to all the gods that Ulysses might return; -when, therefore, he saw for certain what mind they were of, Ulysses -said, “It is I, Ulysses, who am here. I have suffered much, but at -last, in the twentieth year, I am come back to my own country. I find -that you two alone of all my servants are glad that I should do so, for -I have not heard any of the others praying for my return. To you two, -therefore, will I unfold the truth as it shall be. If heaven shall -deliver the suitors into my hands, I will find wives for both of you, -will give you house and holding close to my own, and you shall be to me -as though you were brothers and friends of Telemachus. I will now give -you convincing proofs that you may know me and be assured. See, here is -the scar from the boar’s tooth that ripped me when I was out hunting on -Mt. Parnassus with the sons of Autolycus.” - -As he spoke he drew his rags aside from the great scar, and when they -had examined it thoroughly, they both of them wept about Ulysses, threw -their arms round him, and kissed his head and shoulders, while Ulysses -kissed their hands and faces in return. The sun would have gone down -upon their mourning if Ulysses had not checked them and said: - -“Cease your weeping, lest some one should come outside and see us, and -tell those who are within. When you go in, do so separately, not both -together; I will go first, and do you follow afterwards; let this -moreover be the token between us; the suitors will all of them try to -prevent me from getting hold of the bow and quiver; do you, therefore, -Eumaeus, place it in my hands when you are carrying it about, and tell -the women to close the doors of their apartment. If they hear any -groaning or uproar as of men fighting about the house, they must not -come out; they must keep quiet, and stay where they are at their work. -And I charge you, Philoetius, to make fast the doors of the outer -court, and to bind them securely at once.” - -When he had thus spoken, he went back to the house and took the seat -that he had left. Presently, his two servants followed him inside. - -At this moment the bow was in the hands of Eurymachus, who was warming -it by the fire, but even so he could not string it, and he was greatly -grieved. He heaved a deep sigh and said, “I grieve for myself and for -us all; I grieve that I shall have to forgo the marriage, but I do not -care nearly so much about this, for there are plenty of other women in -Ithaca and elsewhere; what I feel most is the fact of our being so -inferior to Ulysses in strength that we cannot string his bow. This -will disgrace us in the eyes of those who are yet unborn.” - -“It shall not be so, Eurymachus,” said Antinous, “and you know it -yourself. Today is the feast of Apollo throughout all the land; who can -string a bow on such a day as this? Put it on one side—as for the axes -they can stay where they are, for no one is likely to come to the house -and take them away: let the cupbearer go round with his cups, that we -may make our drink-offerings and drop this matter of the bow; we will -tell Melanthius to bring us in some goats tomorrow—the best he has; we -can then offer thigh bones to Apollo the mighty archer, and again make -trial of the bow, so as to bring the contest to an end.” - -The rest approved his words, and thereon men servants poured water over -the hands of the guests, while pages filled the mixing-bowls with wine -and water and handed it round after giving every man his -drink-offering. Then, when they had made their offerings and had drunk -each as much as he desired, Ulysses craftily said:— - -“Suitors of the illustrious queen, listen that I may speak even as I am -minded. I appeal more especially to Eurymachus, and to Antinous who has -just spoken with so much reason. Cease shooting for the present and -leave the matter to the gods, but in the morning let heaven give -victory to whom it will. For the moment, however, give me the bow that -I may prove the power of my hands among you all, and see whether I -still have as much strength as I used to have, or whether travel and -neglect have made an end of it.” - -This made them all very angry, for they feared he might string the bow, -Antinous therefore rebuked him fiercely saying, “Wretched creature, you -have not so much as a grain of sense in your whole body; you ought to -think yourself lucky in being allowed to dine unharmed among your -betters, without having any smaller portion served you than we others -have had, and in being allowed to hear our conversation. No other -beggar or stranger has been allowed to hear what we say among -ourselves; the wine must have been doing you a mischief, as it does -with all those who drink immoderately. It was wine that inflamed the -Centaur Eurytion when he was staying with Peirithous among the -Lapithae. When the wine had got into his head, he went mad and did ill -deeds about the house of Peirithous; this angered the heroes who were -there assembled, so they rushed at him and cut off his ears and -nostrils; then they dragged him through the doorway out of the house, -so he went away crazed, and bore the burden of his crime, bereft of -understanding. Henceforth, therefore, there was war between mankind and -the centaurs, but he brought it upon himself through his own -drunkenness. In like manner I can tell you that it will go hardly with -you if you string the bow: you will find no mercy from any one here, -for we shall at once ship you off to king Echetus, who kills every one -that comes near him: you will never get away alive, so drink and keep -quiet without getting into a quarrel with men younger than yourself.” - -Penelope then spoke to him. “Antinous,” said she, “it is not right that -you should ill-treat any guest of Telemachus who comes to this house. -If the stranger should prove strong enough to string the mighty bow of -Ulysses, can you suppose that he would take me home with him and make -me his wife? Even the man himself can have no such idea in his mind: -none of you need let that disturb his feasting; it would be out of all -reason.” - -“Queen Penelope,” answered Eurymachus, “we do not suppose that this man -will take you away with him; it is impossible; but we are afraid lest -some of the baser sort, men or women among the Achaeans, should go -gossiping about and say, ‘These suitors are a feeble folk; they are -paying court to the wife of a brave man whose bow not one of them was -able to string, and yet a beggarly tramp who came to the house strung -it at once and sent an arrow through the iron.’ This is what will be -said, and it will be a scandal against us.” - -“Eurymachus,” Penelope answered, “people who persist in eating up the -estate of a great chieftain and dishonouring his house must not expect -others to think well of them. Why then should you mind if men talk as -you think they will? This stranger is strong and well-built, he says -moreover that he is of noble birth. Give him the bow, and let us see -whether he can string it or no. I say—and it shall surely be—that if -Apollo vouchsafes him the glory of stringing it, I will give him a -cloak and shirt of good wear, with a javelin to keep off dogs and -robbers, and a sharp sword. I will also give him sandals, and will see -him sent safely wherever he wants to go.” - -Then Telemachus said, “Mother, I am the only man either in Ithaca or in -the islands that are over against Elis who has the right to let any one -have the bow or to refuse it. No one shall force me one way or the -other, not even though I choose to make the stranger a present of the -bow outright, and let him take it away with him. Go, then, within the -house and busy yourself with your daily duties, your loom, your -distaff, and the ordering of your servants. This bow is a man’s matter, -and mine above all others, for it is I who am master here.” - -She went wondering back into the house, and laid her son’s saying in -her heart. Then going upstairs with her handmaids into her room, she -mourned her dear husband till Minerva sent sweet sleep over her -eyelids. - -The swineherd now took up the bow and was for taking it to Ulysses, but -the suitors clamoured at him from all parts of the cloisters, and one -of them said, “You idiot, where are you taking the bow to? Are you out -of your wits? If Apollo and the other gods will grant our prayer, your -own boarhounds shall get you into some quiet little place, and worry -you to death.” - -Eumaeus was frightened at the outcry they all raised, so he put the bow -down then and there, but Telemachus shouted out at him from the other -side of the cloisters, and threatened him saying, “Father Eumaeus, -bring the bow on in spite of them, or young as I am I will pelt you -with stones back to the country, for I am the better man of the two. I -wish I was as much stronger than all the other suitors in the house as -I am than you, I would soon send some of them off sick and sorry, for -they mean mischief.” - -Thus did he speak, and they all of them laughed heartily, which put -them in a better humour with Telemachus; so Eumaeus brought the bow on -and placed it in the hands of Ulysses. When he had done this, he called -Euryclea apart and said to her, “Euryclea, Telemachus says you are to -close the doors of the women’s apartments. If they hear any groaning or -uproar as of men fighting about the house, they are not to come out, -but are to keep quiet and stay where they are at their work.” - -Euryclea did as she was told and closed the doors of the women’s -apartments. - -Meanwhile Philoetius slipped quietly out and made fast the gates of the -outer court. There was a ship’s cable of byblus fibre lying in the -gatehouse, so he made the gates fast with it and then came in again, -resuming the seat that he had left, and keeping an eye on Ulysses, who -had now got the bow in his hands, and was turning it every way about, -and proving it all over to see whether the worms had been eating into -its two horns during his absence. Then would one turn towards his -neighbour saying, “This is some tricky old bow-fancier; either he has -got one like it at home, or he wants to make one, in such workmanlike -style does the old vagabond handle it.” - -Another said, “I hope he may be no more successful in other things than -he is likely to be in stringing this bow.” - -But Ulysses, when he had taken it up and examined it all over, strung -it as easily as a skilled bard strings a new peg of his lyre and makes -the twisted gut fast at both ends. Then he took it in his right hand to -prove the string, and it sang sweetly under his touch like the -twittering of a swallow. The suitors were dismayed, and turned colour -as they heard it; at that moment, moreover, Jove thundered loudly as a -sign, and the heart of Ulysses rejoiced as he heard the omen that the -son of scheming Saturn had sent him. - -He took an arrow that was lying upon the table165—for those which the -Achaeans were so shortly about to taste were all inside the quiver—he -laid it on the centre-piece of the bow, and drew the notch of the arrow -and the string toward him, still seated on his seat. When he had taken -aim he let fly, and his arrow pierced every one of the handle-holes of -the axes from the first onwards till it had gone right through them, -and into the outer courtyard. Then he said to Telemachus: - -“Your guest has not disgraced you, Telemachus. I did not miss what I -aimed at, and I was not long in stringing my bow. I am still strong, -and not as the suitors twit me with being. Now, however, it is time for -the Achaeans to prepare supper while there is still daylight, and then -otherwise to disport themselves with song and dance which are the -crowning ornaments of a banquet.” - -As he spoke he made a sign with his eyebrows, and Telemachus girded on -his sword, grasped his spear, and stood armed beside his father’s seat. - - - - -BOOK XXII - - -THE KILLING OF THE SUITORS—THE MAIDS WHO HAVE MISCONDUCTED THEMSELVES -ARE MADE TO CLEANSE THE CLOISTERS AND ARE THEN HANGED. - - -Then Ulysses tore off his rags, and sprang on to the broad pavement -with his bow and his quiver full of arrows. He shed the arrows on to -the ground at his feet and said, “The mighty contest is at an end. I -will now see whether Apollo will vouchsafe it to me to hit another mark -which no man has yet hit.” - -On this he aimed a deadly arrow at Antinous, who was about to take up a -two-handled gold cup to drink his wine and already had it in his hands. -He had no thought of death—who amongst all the revellers would think -that one man, however brave, would stand alone among so many and kill -him? The arrow struck Antinous in the throat, and the point went clean -through his neck, so that he fell over and the cup dropped from his -hand, while a thick stream of blood gushed from his nostrils. He kicked -the table from him and upset the things on it, so that the bread and -roasted meats were all soiled as they fell over on to the ground.166 -The suitors were in an uproar when they saw that a man had been hit; -they sprang in dismay one and all of them from their seats and looked -everywhere towards the walls, but there was neither shield nor spear, -and they rebuked Ulysses very angrily. “Stranger,” said they, “you -shall pay for shooting people in this way: you shall see no other -contest; you are a doomed man; he whom you have slain was the foremost -youth in Ithaca, and the vultures shall devour you for having killed -him.” - -Thus they spoke, for they thought that he had killed Antinous by -mistake, and did not perceive that death was hanging over the head of -every one of them. But Ulysses glared at them and said: - -“Dogs, did you think that I should not come back from Troy? You have -wasted my substance,167 have forced my women servants to lie with you, -and have wooed my wife while I was still living. You have feared -neither God nor man, and now you shall die.” - -They turned pale with fear as he spoke, and every man looked round -about to see whither he might fly for safety, but Eurymachus alone -spoke. - -“If you are Ulysses,” said he, “then what you have said is just. We -have done much wrong on your lands and in your house. But Antinous who -was the head and front of the offending lies low already. It was all -his doing. It was not that he wanted to marry Penelope; he did not so -much care about that; what he wanted was something quite different, and -Jove has not vouchsafed it to him; he wanted to kill your son and to be -chief man in Ithaca. Now, therefore, that he has met the death which -was his due, spare the lives of your people. We will make everything -good among ourselves, and pay you in full for all that we have eaten -and drunk. Each one of us shall pay you a fine worth twenty oxen, and -we will keep on giving you gold and bronze till your heart is softened. -Until we have done this no one can complain of your being enraged -against us.” - -Ulysses again glared at him and said, “Though you should give me all -that you have in the world both now and all that you ever shall have, I -will not stay my hand till I have paid all of you in full. You must -fight, or fly for your lives; and fly, not a man of you shall.” - -Their hearts sank as they heard him, but Eurymachus again spoke saying: - -“My friends, this man will give us no quarter. He will stand where he -is and shoot us down till he has killed every man among us. Let us then -show fight; draw your swords, and hold up the tables to shield you from -his arrows. Let us have at him with a rush, to drive him from the -pavement and doorway: we can then get through into the town, and raise -such an alarm as shall soon stay his shooting.” - -As he spoke he drew his keen blade of bronze, sharpened on both sides, -and with a loud cry sprang towards Ulysses, but Ulysses instantly shot -an arrow into his breast that caught him by the nipple and fixed itself -in his liver. He dropped his sword and fell doubled up over his table. -The cup and all the meats went over on to the ground as he smote the -earth with his forehead in the agonies of death, and he kicked the -stool with his feet until his eyes were closed in darkness. - -Then Amphinomus drew his sword and made straight at Ulysses to try and -get him away from the door; but Telemachus was too quick for him, and -struck him from behind; the spear caught him between the shoulders and -went right through his chest, so that he fell heavily to the ground and -struck the earth with his forehead. Then Telemachus sprang away from -him, leaving his spear still in the body, for he feared that if he -stayed to draw it out, some one of the Achaeans might come up and hack -at him with his sword, or knock him down, so he set off at a run, and -immediately was at his father’s side. Then he said: - -“Father, let me bring you a shield, two spears, and a brass helmet for -your temples. I will arm myself as well, and will bring other armour -for the swineherd and the stockman, for we had better be armed.” - -“Run and fetch them,” answered Ulysses, “while my arrows hold out, or -when I am alone they may get me away from the door.” - -Telemachus did as his father said, and went off to the store room where -the armour was kept. He chose four shields, eight spears, and four -brass helmets with horse-hair plumes. He brought them with all speed to -his father, and armed himself first, while the stockman and the -swineherd also put on their armour, and took their places near Ulysses. -Meanwhile Ulysses, as long as his arrows lasted, had been shooting the -suitors one by one, and they fell thick on one another: when his arrows -gave out, he set the bow to stand against the end wall of the house by -the door post, and hung a shield four hides thick about his shoulders; -on his comely head he set his helmet, well wrought with a crest of -horse-hair that nodded menacingly above it,168 and he grasped two -redoubtable bronze-shod spears. - -Now there was a trap door169 on the wall, while at one end of the -pavement170 there was an exit leading to a narrow passage, and this -exit was closed by a well-made door. Ulysses told Philoetius to stand -by this door and guard it, for only one person could attack it at a -time. But Agelaus shouted out, “Cannot some one go up to the trap door -and tell the people what is going on? Help would come at once, and we -should soon make an end of this man and his shooting.” - -“This may not be, Agelaus,” answered Melanthius, “the mouth of the -narrow passage is dangerously near the entrance to the outer court. One -brave man could prevent any number from getting in. But I know what I -will do, I will bring you arms from the store-room, for I am sure it is -there that Ulysses and his son have put them.” - -On this the goatherd Melanthius went by back passages to the store-room -of Ulysses’ house. There he chose twelve shields, with as many helmets -and spears, and brought them back as fast as he could to give them to -the suitors. Ulysses’ heart began to fail him when he saw the -suitors171 putting on their armour and brandishing their spears. He saw -the greatness of the danger, and said to Telemachus, “Some one of the -women inside is helping the suitors against us, or it may be -Melanthius.” - -Telemachus answered, “The fault, father, is mine, and mine only; I left -the store room door open, and they have kept a sharper look out than I -have. Go, Eumaeus, put the door to, and see whether it is one of the -women who is doing this, or whether, as I suspect, it is Melanthius the -son of Dolius.” - -Thus did they converse. Meanwhile Melanthius was again going to the -store room to fetch more armour, but the swineherd saw him and said to -Ulysses who was beside him, “Ulysses, noble son of Laertes, it is that -scoundrel Melanthius, just as we suspected, who is going to the store -room. Say, shall I kill him, if I can get the better of him, or shall I -bring him here that you may take your own revenge for all the many -wrongs that he has done in your house?” - -Ulysses answered, “Telemachus and I will hold these suitors in check, -no matter what they do; go back both of you and bind Melanthius’ hands -and feet behind him. Throw him into the store room and make the door -fast behind you; then fasten a noose about his body, and string him -close up to the rafters from a high bearing-post,172 that he may linger -on in an agony.” - -Thus did he speak, and they did even as he had said; they went to the -store room, which they entered before Melanthius saw them, for he was -busy searching for arms in the innermost part of the room, so the two -took their stand on either side of the door and waited. By and by -Melanthius came out with a helmet in one hand, and an old dry-rotted -shield in the other, which had been borne by Laertes when he was young, -but which had been long since thrown aside, and the straps had become -unsewn; on this the two seized him, dragged him back by the hair, and -threw him struggling to the ground. They bent his hands and feet well -behind his back, and bound them tight with a painful bond as Ulysses -had told them; then they fastened a noose about his body and strung him -up from a high pillar till he was close up to the rafters, and over him -did you then vaunt, O swineherd Eumaeus saying, “Melanthius, you will -pass the night on a soft bed as you deserve. You will know very well -when morning comes from the streams of Oceanus, and it is time for you -to be driving in your goats for the suitors to feast on.” - -There, then, they left him in very cruel bondage, and having put on -their armour they closed the door behind them and went back to take -their places by the side of Ulysses; whereon the four men stood in the -cloister, fierce and full of fury; nevertheless, those who were in the -body of the court were still both brave and many. Then Jove’s daughter -Minerva came up to them, having assumed the voice and form of Mentor. -Ulysses was glad when he saw her and said, “Mentor, lend me your help, -and forget not your old comrade, nor the many good turns he has done -you. Besides, you are my age-mate.” - -But all the time he felt sure it was Minerva, and the suitors from the -other side raised an uproar when they saw her. Agelaus was the first to -reproach her. “Mentor,” he cried, “do not let Ulysses beguile you into -siding with him and fighting the suitors. This is what we will do: when -we have killed these people, father and son, we will kill you too. You -shall pay for it with your head, and when we have killed you, we will -take all you have, in doors or out, and bring it into hotch-pot with -Ulysses’ property; we will not let your sons live in your house, nor -your daughters, nor shall your widow continue to live in the city of -Ithaca.” - -This made Minerva still more furious, so she scolded Ulysses very -angrily.173 “Ulysses,” said she, “your strength and prowess are no -longer what they were when you fought for nine long years among the -Trojans about the noble lady Helen. You killed many a man in those -days, and it was through your stratagem that Priam’s city was taken. -How comes it that you are so lamentably less valiant now that you are -on your own ground, face to face with the suitors in your own house? -Come on, my good fellow, stand by my side and see how Mentor, son of -Alcimus shall fight your foes and requite your kindnesses conferred -upon him.” - -But she would not give him full victory as yet, for she wished still -further to prove his own prowess and that of his brave son, so she flew -up to one of the rafters in the roof of the cloister and sat upon it in -the form of a swallow. - -Meanwhile Agelaus son of Damastor, Eurynomus, Amphimedon, Demoptolemus, -Pisander, and Polybus son of Polyctor bore the brunt of the fight upon -the suitors’ side; of all those who were still fighting for their lives -they were by far the most valiant, for the others had already fallen -under the arrows of Ulysses. Agelaus shouted to them and said, “My -friends, he will soon have to leave off, for Mentor has gone away after -having done nothing for him but brag. They are standing at the doors -unsupported. Do not aim at him all at once, but six of you throw your -spears first, and see if you cannot cover yourselves with glory by -killing him. When he has fallen we need not be uneasy about the -others.” - -They threw their spears as he bade them, but Minerva made them all of -no effect. One hit the door post; another went against the door; the -pointed shaft of another struck the wall; and as soon as they had -avoided all the spears of the suitors Ulysses said to his own men, “My -friends, I should say we too had better let drive into the middle of -them, or they will crown all the harm they have done us by killing us -outright.” - -They therefore aimed straight in front of them and threw their spears. -Ulysses killed Demoptolemus, Telemachus Euryades, Eumaeus Elatus, while -the stockman killed Pisander. These all bit the dust, and as the others -drew back into a corner Ulysses and his men rushed forward and regained -their spears by drawing them from the bodies of the dead. - -The suitors now aimed a second time, but again Minerva made their -weapons for the most part without effect. One hit a bearing-post of the -cloister; another went against the door; while the pointed shaft of -another struck the wall. Still, Amphimedon just took a piece of the top -skin from off Telemachus’s wrist, and Ctesippus managed to graze -Eumaeus’s shoulder above his shield; but the spear went on and fell to -the ground. Then Ulysses and his men let drive into the crowd of -suitors. Ulysses hit Eurydamas, Telemachus Amphimedon, and Eumaeus -Polybus. After this the stockman hit Ctesippus in the breast, and -taunted him saying, “Foul-mouthed son of Polytherses, do not be so -foolish as to talk wickedly another time, but let heaven direct your -speech, for the gods are far stronger than men. I make you a present of -this advice to repay you for the foot which you gave Ulysses when he -was begging about in his own house.” - -Thus spoke the stockman, and Ulysses struck the son of Damastor with a -spear in close fight, while Telemachus hit Leocritus son of Evenor in -the belly, and the dart went clean through him, so that he fell forward -full on his face upon the ground. Then Minerva from her seat on the -rafter held up her deadly aegis, and the hearts of the suitors quailed. -They fled to the other end of the court like a herd of cattle maddened -by the gadfly in early summer when the days are at their longest. As -eagle-beaked, crook-taloned vultures from the mountains swoop down on -the smaller birds that cower in flocks upon the ground, and kill them, -for they cannot either fight or fly, and lookers on enjoy the -sport—even so did Ulysses and his men fall upon the suitors and smite -them on every side. They made a horrible groaning as their brains were -being battered in, and the ground seethed with their blood. - -Leiodes then caught the knees of Ulysses and said, “Ulysses I beseech -you have mercy upon me and spare me. I never wronged any of the women -in your house either in word or deed, and I tried to stop the others. I -saw them, but they would not listen, and now they are paying for their -folly. I was their sacrificing priest; if you kill me, I shall die -without having done anything to deserve it, and shall have got no -thanks for all the good that I did.” - -Ulysses looked sternly at him and answered, “If you were their -sacrificing priest, you must have prayed many a time that it might be -long before I got home again, and that you might marry my wife and have -children by her. Therefore you shall die.” - -With these words he picked up the sword that Agelaus had dropped when -he was being killed, and which was lying upon the ground. Then he -struck Leiodes on the back of his neck, so that his head fell rolling -in the dust while he was yet speaking. - -The minstrel Phemius son of Terpes—he who had been forced by the -suitors to sing to them—now tried to save his life. He was standing -near towards the trap door,174 and held his lyre in his hand. He did -not know whether to fly out of the cloister and sit down by the altar -of Jove that was in the outer court, and on which both Laertes and -Ulysses had offered up the thigh bones of many an ox, or whether to go -straight up to Ulysses and embrace his knees, but in the end he deemed -it best to embrace Ulysses’ knees. So he laid his lyre on the ground -between the mixing bowl 175 and the silver-studded seat; then going up -to Ulysses he caught hold of his knees and said, “Ulysses, I beseech -you have mercy on me and spare me. You will be sorry for it afterwards -if you kill a bard who can sing both for gods and men as I can. I make -all my lays myself, and heaven visits me with every kind of -inspiration. I would sing to you as though you were a god, do not -therefore be in such a hurry to cut my head off. Your own son -Telemachus will tell you that I did not want to frequent your house and -sing to the suitors after their meals, but they were too many and too -strong for me, so they made me.” - -Telemachus heard him, and at once went up to his father. “Hold!” he -cried, “the man is guiltless, do him no hurt; and we will spare Medon -too, who was always good to me when I was a boy, unless Philoetius or -Eumaeus has already killed him, or he has fallen in your way when you -were raging about the court.” - -Medon caught these words of Telemachus, for he was crouching under a -seat beneath which he had hidden by covering himself up with a freshly -flayed heifer’s hide, so he threw off the hide, went up to Telemachus, -and laid hold of his knees. - -“Here I am, my dear sir,” said he, “stay your hand therefore, and tell -your father, or he will kill me in his rage against the suitors for -having wasted his substance and been so foolishly disrespectful to -yourself.” - -Ulysses smiled at him and answered, “Fear not; Telemachus has saved -your life, that you may know in future, and tell other people, how -greatly better good deeds prosper than evil ones. Go, therefore, -outside the cloisters into the outer court, and be out of the way of -the slaughter—you and the bard—while I finish my work here inside.” - -The pair went into the outer court as fast as they could, and sat down -by Jove’s great altar, looking fearfully round, and still expecting -that they would be killed. Then Ulysses searched the whole court -carefully over, to see if anyone had managed to hide himself and was -still living, but he found them all lying in the dust and weltering in -their blood. They were like fishes which fishermen have netted out of -the sea, and thrown upon the beach to lie gasping for water till the -heat of the sun makes an end of them. Even so were the suitors lying -all huddled up one against the other. - -Then Ulysses said to Telemachus, “Call nurse Euryclea; I have something -to say to her.” - -Telemachus went and knocked at the door of the women’s room. “Make -haste,” said he, “you old woman who have been set over all the other -women in the house. Come outside; my father wishes to speak to you.” - -When Euryclea heard this she unfastened the door of the women’s room -and came out, following Telemachus. She found Ulysses among the corpses -bespattered with blood and filth like a lion that has just been -devouring an ox, and his breast and both his cheeks are all bloody, so -that he is a fearful sight; even so was Ulysses besmirched from head to -foot with gore. When she saw all the corpses and such a quantity of -blood, she was beginning to cry out for joy, for she saw that a great -deed had been done; but Ulysses checked her, “Old woman,” said he, -“rejoice in silence; restrain yourself, and do not make any noise about -it; it is an unholy thing to vaunt over dead men. Heaven’s doom and -their own evil deeds have brought these men to destruction, for they -respected no man in the whole world, neither rich nor poor, who came -near them, and they have come to a bad end as a punishment for their -wickedness and folly. Now, however, tell me which of the women in the -house have misconducted themselves, and who are innocent.”176 - -“I will tell you the truth, my son,” answered Euryclea. “There are -fifty women in the house whom we teach to do things, such as carding -wool, and all kinds of household work. Of these, twelve in all177 have -misbehaved, and have been wanting in respect to me, and also to -Penelope. They showed no disrespect to Telemachus, for he has only -lately grown and his mother never permitted him to give orders to the -female servants; but let me go upstairs and tell your wife all that has -happened, for some god has been sending her to sleep.” - -“Do not wake her yet,” answered Ulysses, “but tell the women who have -misconducted themselves to come to me.” - -Euryclea left the cloister to tell the women, and make them come to -Ulysses; in the meantime he called Telemachus, the stockman, and the -swineherd. “Begin,” said he, “to remove the dead, and make the women -help you. Then, get sponges and clean water to swill down the tables -and seats. When you have thoroughly cleansed the whole cloisters, take -the women into the space between the domed room and the wall of the -outer court, and run them through with your swords till they are quite -dead, and have forgotten all about love and the way in which they used -to lie in secret with the suitors.” - -On this the women came down in a body, weeping and wailing bitterly. -First they carried the dead bodies out, and propped them up against one -another in the gatehouse. Ulysses ordered them about and made them do -their work quickly, so they had to carry the bodies out. When they had -done this, they cleaned all the tables and seats with sponges and -water, while Telemachus and the two others shovelled up the blood and -dirt from the ground, and the women carried it all away and put it out -of doors. Then when they had made the whole place quite clean and -orderly, they took the women out and hemmed them in the narrow space -between the wall of the domed room and that of the yard, so that they -could not get away: and Telemachus said to the other two, “I shall not -let these women die a clean death, for they were insolent to me and my -mother, and used to sleep with the suitors.” - -So saying he made a ship’s cable fast to one of the bearing-posts that -supported the roof of the domed room, and secured it all around the -building, at a good height, lest any of the women’s feet should touch -the ground; and as thrushes or doves beat against a net that has been -set for them in a thicket just as they were getting to their nest, and -a terrible fate awaits them, even so did the women have to put their -heads in nooses one after the other and die most miserably.178 Their -feet moved convulsively for a while, but not for very long. - -As for Melanthius, they took him through the cloister into the inner -court. There they cut off his nose and his ears; they drew out his -vitals and gave them to the dogs raw, and then in their fury they cut -off his hands and his feet. - -When they had done this they washed their hands and feet and went back -into the house, for all was now over; and Ulysses said to the dear old -nurse Euryclea, “Bring me sulphur, which cleanses all pollution, and -fetch fire also that I may burn it, and purify the cloisters. Go, -moreover, and tell Penelope to come here with her attendants, and also -all the maidservants that are in the house.” - -“All that you have said is true,” answered Euryclea, “but let me bring -you some clean clothes—a shirt and cloak. Do not keep these rags on -your back any longer. It is not right.” - -“First light me a fire,” replied Ulysses. - -She brought the fire and sulphur, as he had bidden her, and Ulysses -thoroughly purified the cloisters and both the inner and outer courts. -Then she went inside to call the women and tell them what had happened; -whereon they came from their apartment with torches in their hands, and -pressed round Ulysses to embrace him, kissing his head and shoulders -and taking hold of his hands. It made him feel as if he should like to -weep, for he remembered every one of them.179 - - - - -BOOK XXIII - - -PENELOPE EVENTUALLY RECOGNISES HER HUSBAND—EARLY IN THE MORNING -ULYSSES, TELEMACHUS, EUMAEUS, AND PHILOETIUS LEAVE THE TOWN. - - -Euryclea now went upstairs laughing to tell her mistress that her dear -husband had come home. Her aged knees became young again and her feet -were nimble for joy as she went up to her mistress and bent over her -head to speak to her. “Wake up Penelope, my dear child,” she exclaimed, -“and see with your own eyes something that you have been wanting this -long time past. Ulysses has at last indeed come home again, and has -killed the suitors who were giving so much trouble in his house, eating -up his estate and ill treating his son.” - -“My good nurse,” answered Penelope, “you must be mad. The gods -sometimes send some very sensible people out of their minds, and make -foolish people become sensible. This is what they must have been doing -to you; for you always used to be a reasonable person. Why should you -thus mock me when I have trouble enough already—talking such nonsense, -and waking me up out of a sweet sleep that had taken possession of my -eyes and closed them? I have never slept so soundly from the day my -poor husband went to that city with the ill-omened name. Go back again -into the women’s room; if it had been any one else who had woke me up -to bring me such absurd news I should have sent her away with a severe -scolding. As it is your age shall protect you.” - -“My dear child,” answered Euryclea, “I am not mocking you. It is quite -true as I tell you that Ulysses is come home again. He was the stranger -whom they all kept on treating so badly in the cloister. Telemachus -knew all the time that he was come back, but kept his father’s secret -that he might have his revenge on all these wicked people.” - -Then Penelope sprang up from her couch, threw her arms round Euryclea, -and wept for joy. “But my dear nurse,” said she, “explain this to me; -if he has really come home as you say, how did he manage to overcome -the wicked suitors single handed, seeing what a number of them there -always were?” - -“I was not there,” answered Euryclea, “and do not know; I only heard -them groaning while they were being killed. We sat crouching and -huddled up in a corner of the women’s room with the doors closed, till -your son came to fetch me because his father sent him. Then I found -Ulysses standing over the corpses that were lying on the ground all -round him, one on top of the other. You would have enjoyed it if you -could have seen him standing there all bespattered with blood and -filth, and looking just like a lion. But the corpses are now all piled -up in the gatehouse that is in the outer court, and Ulysses has lit a -great fire to purify the house with sulphur. He has sent me to call -you, so come with me that you may both be happy together after all; for -now at last the desire of your heart has been fulfilled; your husband -is come home to find both wife and son alive and well, and to take his -revenge in his own house on the suitors who behaved so badly to him.” - -“My dear nurse,” said Penelope, “do not exult too confidently over all -this. You know how delighted every one would be to see Ulysses come -home—more particularly myself, and the son who has been born to both of -us; but what you tell me cannot be really true. It is some god who is -angry with the suitors for their great wickedness, and has made an end -of them; for they respected no man in the whole world, neither rich nor -poor, who came near them, and they have come to a bad end in -consequence of their iniquity; Ulysses is dead far away from the -Achaean land; he will never return home again.” - -Then nurse Euryclea said, “My child, what are you talking about? but -you were all hard of belief and have made up your mind that your -husband is never coming, although he is in the house and by his own -fire side at this very moment. Besides I can give you another proof; -when I was washing him I perceived the scar which the wild boar gave -him, and I wanted to tell you about it, but in his wisdom he would not -let me, and clapped his hands over my mouth; so come with me and I will -make this bargain with you—if I am deceiving you, you may have me -killed by the most cruel death you can think of.” - -“My dear nurse,” said Penelope, “however wise you may be you can hardly -fathom the counsels of the gods. Nevertheless, we will go in search of -my son, that I may see the corpses of the suitors, and the man who has -killed them.” - -On this she came down from her upper room, and while doing so she -considered whether she should keep at a distance from her husband and -question him, or whether she should at once go up to him and embrace -him. When, however, she had crossed the stone floor of the cloister, -she sat down opposite Ulysses by the fire, against the wall at right -angles180 [to that by which she had entered], while Ulysses sat near -one of the bearing-posts, looking upon the ground, and waiting to see -what his brave wife would say to him when she saw him. For a long time -she sat silent and as one lost in amazement. At one moment she looked -him full in the face, but then again directly, she was misled by his -shabby clothes and failed to recognise him,181 till Telemachus began to -reproach her and said: - -“Mother—but you are so hard that I cannot call you by such a name—why -do you keep away from my father in this way? Why do you not sit by his -side and begin talking to him and asking him questions? No other woman -could bear to keep away from her husband when he had come back to her -after twenty years of absence, and after having gone through so much; -but your heart always was as hard as a stone.” - -Penelope answered, “My son, I am so lost in astonishment that I can -find no words in which either to ask questions or to answer them. I -cannot even look him straight in the face. Still, if he really is -Ulysses come back to his own home again, we shall get to understand one -another better by and by, for there are tokens with which we two are -alone acquainted, and which are hidden from all others.” - -Ulysses smiled at this, and said to Telemachus, “Let your mother put me -to any proof she likes; she will make up her mind about it presently. -She rejects me for the moment and believes me to be somebody else, -because I am covered with dirt and have such bad clothes on; let us, -however, consider what we had better do next. When one man has killed -another—even though he was not one who would leave many friends to take -up his quarrel—the man who has killed him must still say good bye to -his friends and fly the country; whereas we have been killing the stay -of a whole town, and all the picked youth of Ithaca. I would have you -consider this matter.” - -“Look to it yourself, father,” answered Telemachus, “for they say you -are the wisest counsellor in the world, and that there is no other -mortal man who can compare with you. We will follow you with right good -will, nor shall you find us fail you in so far as our strength holds -out.” - -“I will say what I think will be best,” answered Ulysses. “First wash -and put your shirts on; tell the maids also to go to their own room and -dress; Phemius shall then strike up a dance tune on his lyre, so that -if people outside hear, or any of the neighbours, or some one going -along the street happens to notice it, they may think there is a -wedding in the house, and no rumours about the death of the suitors -will get about in the town, before we can escape to the woods upon my -own land. Once there, we will settle which of the courses heaven -vouchsafes us shall seem wisest.” - -Thus did he speak, and they did even as he had said. First they washed -and put their shirts on, while the women got ready. Then Phemius took -his lyre and set them all longing for sweet song and stately dance. The -house re-echoed with the sound of men and women dancing, and the people -outside said, “I suppose the queen has been getting married at last. -She ought to be ashamed of herself for not continuing to protect her -husband’s property until he comes home.”182 - -This was what they said, but they did not know what it was that had -been happening. The upper servant Eurynome washed and anointed Ulysses -in his own house and gave him a shirt and cloak, while Minerva made him -look taller and stronger than before; she also made the hair grow thick -on the top of his head, and flow down in curls like hyacinth blossoms; -she glorified him about the head and shoulders just as a skilful -workman who has studied art of all kinds under Vulcan or Minerva—and -his work is full of beauty—enriches a piece of silver plate by gilding -it. He came from the bath looking like one of the immortals, and sat -down opposite his wife on the seat he had left. “My dear,” said he, -“heaven has endowed you with a heart more unyielding than woman ever -yet had. No other woman could bear to keep away from her husband when -he had come back to her after twenty years of absence, and after having -gone through so much. But come, nurse, get a bed ready for me; I will -sleep alone, for this woman has a heart as hard as iron.” - -“My dear,” answered Penelope, “I have no wish to set myself up, nor to -depreciate you; but I am not struck by your appearance, for I very well -remember what kind of a man you were when you set sail from Ithaca. -Nevertheless, Euryclea, take his bed outside the bed chamber that he -himself built. Bring the bed outside this room, and put bedding upon it -with fleeces, good coverlets, and blankets.” - -She said this to try him, but Ulysses was very angry and said, “Wife, I -am much displeased at what you have just been saying. Who has been -taking my bed from the place in which I left it? He must have found it -a hard task, no matter how skilled a workman he was, unless some god -came and helped him to shift it. There is no man living, however strong -and in his prime, who could move it from its place, for it is a -marvellous curiosity which I made with my very own hands. There was a -young olive growing within the precincts of the house, in full vigour, -and about as thick as a bearing-post. I built my room round this with -strong walls of stone and a roof to cover them, and I made the doors -strong and well-fitting. Then I cut off the top boughs of the olive -tree and left the stump standing. This I dressed roughly from the root -upwards and then worked with carpenter’s tools well and skilfully, -straightening my work by drawing a line on the wood, and making it into -a bed-prop. I then bored a hole down the middle, and made it the -centre-post of my bed, at which I worked till I had finished it, -inlaying it with gold and silver; after this I stretched a hide of -crimson leather from one side of it to the other. So you see I know all -about it, and I desire to learn whether it is still there, or whether -any one has been removing it by cutting down the olive tree at its -roots.” - -When she heard the sure proofs Ulysses now gave her, she fairly broke -down. She flew weeping to his side, flung her arms about his neck, and -kissed him. “Do not be angry with me Ulysses,” she cried, “you, who are -the wisest of mankind. We have suffered, both of us. Heaven has denied -us the happiness of spending our youth, and of growing old, together; -do not then be aggrieved or take it amiss that I did not embrace you -thus as soon as I saw you. I have been shuddering all the time through -fear that someone might come here and deceive me with a lying story; -for there are many very wicked people going about. Jove’s daughter -Helen would never have yielded herself to a man from a foreign country, -if she had known that the sons of Achaeans would come after her and -bring her back. Heaven put it in her heart to do wrong, and she gave no -thought to that sin, which has been the source of all our sorrows. Now, -however, that you have convinced me by showing that you know all about -our bed (which no human being has ever seen but you and I and a single -maidservant, the daughter of Actor, who was given me by my father on my -marriage, and who keeps the doors of our room) hard of belief though I -have been I can mistrust no longer.” - -Then Ulysses in his turn melted, and wept as he clasped his dear and -faithful wife to his bosom. As the sight of land is welcome to men who -are swimming towards the shore, when Neptune has wrecked their ship -with the fury of his winds and waves; a few alone reach the land, and -these, covered with brine, are thankful when they find themselves on -firm ground and out of danger—even so was her husband welcome to her as -she looked upon him, and she could not tear her two fair arms from -about his neck. Indeed they would have gone on indulging their sorrow -till rosy-fingered morn appeared, had not Minerva determined otherwise, -and held night back in the far west, while she would not suffer Dawn to -leave Oceanus, nor to yoke the two steeds Lampus and Phaethon that bear -her onward to break the day upon mankind. - -At last, however, Ulysses said, “Wife, we have not yet reached the end -of our troubles. I have an unknown amount of toil still to undergo. It -is long and difficult, but I must go through with it, for thus the -shade of Teiresias prophesied concerning me, on the day when I went -down into Hades to ask about my return and that of my companions. But -now let us go to bed, that we may lie down and enjoy the blessed boon -of sleep.” - -“You shall go to bed as soon as you please,” replied Penelope, “now -that the gods have sent you home to your own good house and to your -country. But as heaven has put it in your mind to speak of it, tell me -about the task that lies before you. I shall have to hear about it -later, so it is better that I should be told at once.” - -“My dear,” answered Ulysses, “why should you press me to tell you? -Still, I will not conceal it from you, though you will not like it. I -do not like it myself, for Teiresias bade me travel far and wide, -carrying an oar, till I came to a country where the people have never -heard of the sea, and do not even mix salt with their food. They know -nothing about ships, nor oars that are as the wings of a ship. He gave -me this certain token which I will not hide from you. He said that a -wayfarer should meet me and ask me whether it was a winnowing shovel -that I had on my shoulder. On this, I was to fix my oar in the ground -and sacrifice a ram, a bull, and a boar to Neptune; after which I was -to go home and offer hecatombs to all the gods in heaven, one after the -other. As for myself, he said that death should come to me from the -sea, and that my life should ebb away very gently when I was full of -years and peace of mind, and my people should bless me. All this, he -said, should surely come to pass.” - -And Penelope said, “If the gods are going to vouchsafe you a happier -time in your old age, you may hope then to have some respite from -misfortune.” - -Thus did they converse. Meanwhile Eurynome and the nurse took torches -and made the bed ready with soft coverlets; as soon as they had laid -them, the nurse went back into the house to go to her rest, leaving the -bed chamber woman Eurynome183 to show Ulysses and Penelope to bed by -torch light. When she had conducted them to their room she went back, -and they then came joyfully to the rites of their own old bed. -Telemachus, Philoetius, and the swineherd now left off dancing, and -made the women leave off also. They then laid themselves down to sleep -in the cloisters. - -When Ulysses and Penelope had had their fill of love they fell talking -with one another. She told him how much she had had to bear in seeing -the house filled with a crowd of wicked suitors who had killed so many -sheep and oxen on her account, and had drunk so many casks of wine. -Ulysses in his turn told her what he had suffered, and how much trouble -he had himself given to other people. He told her everything, and she -was so delighted to listen that she never went to sleep till he had -ended his whole story. - -He began with his victory over the Cicons, and how he thence reached -the fertile land of the Lotus-eaters. He told her all about the Cyclops -and how he had punished him for having so ruthlessly eaten his brave -comrades; how he then went on to Aeolus, who received him hospitably -and furthered him on his way, but even so he was not to reach home, for -to his great grief a hurricane carried him out to sea again; how he -went on to the Laestrygonian city Telepylos, where the people destroyed -all his ships with their crews, save himself and his own ship only. -Then he told of cunning Circe and her craft, and how he sailed to the -chill house of Hades, to consult the ghost of the Theban prophet -Teiresias, and how he saw his old comrades in arms, and his mother who -bore him and brought him up when he was a child; how he then heard the -wondrous singing of the Sirens, and went on to the wandering rocks and -terrible Charybdis and to Scylla, whom no man had ever yet passed in -safety; how his men then ate the cattle of the sun-god, and how Jove -therefore struck the ship with his thunderbolts, so that all his men -perished together, himself alone being left alive; how at last he -reached the Ogygian island and the nymph Calypso, who kept him there in -a cave, and fed him, and wanted him to marry her, in which case she -intended making him immortal so that he should never grow old, but she -could not persuade him to let her do so; and how after much suffering -he had found his way to the Phaeacians, who had treated him as though -he had been a god, and sent him back in a ship to his own country after -having given him gold, bronze, and raiment in great abundance. This was -the last thing about which he told her, for here a deep sleep took hold -upon him and eased the burden of his sorrows. - -Then Minerva bethought her of another matter. When she deemed that -Ulysses had had both of his wife and of repose, she bade gold-enthroned -Dawn rise out of Oceanus that she might shed light upon mankind. On -this, Ulysses rose from his comfortable bed and said to Penelope, -“Wife, we have both of us had our full share of troubles, you, here, in -lamenting my absence, and I in being prevented from getting home though -I was longing all the time to do so. Now, however, that we have at last -come together, take care of the property that is in the house. As for -the sheep and goats which the wicked suitors have eaten, I will take -many myself by force from other people, and will compel the Achaeans to -make good the rest till they shall have filled all my yards. I am now -going to the wooded lands out in the country to see my father who has -so long been grieved on my account, and to yourself I will give these -instructions, though you have little need of them. At sunrise it will -at once get abroad that I have been killing the suitors; go upstairs, -therefore,184 and stay there with your women. See nobody and ask no -questions.”185 - -As he spoke he girded on his armour. Then he roused Telemachus, -Philoetius, and Eumaeus, and told them all to put on their armour also. -This they did, and armed themselves. When they had done so, they opened -the gates and sallied forth, Ulysses leading the way. It was now -daylight, but Minerva nevertheless concealed them in darkness and led -them quickly out of the town. - - - - -BOOK XXIV - - -THE GHOSTS OF THE SUITORS IN HADES—ULYSSES AND HIS MEN GO TO THE HOUSE -OF LAERTES—THE PEOPLE OF ITHACA COME OUT TO ATTACK ULYSSES, BUT MINERVA -CONCLUDES A PEACE. - - -Then Mercury of Cyllene summoned the ghosts of the suitors, and in his -hand he held the fair golden wand with which he seals men’s eyes in -sleep or wakes them just as he pleases; with this he roused the ghosts -and led them, while they followed whining and gibbering behind him. As -bats fly squealing in the hollow of some great cave, when one of them -has fallen out of the cluster in which they hang, even so did the -ghosts whine and squeal as Mercury the healer of sorrow led them down -into the dark abode of death. When they had passed the waters of -Oceanus and the rock Leucas, they came to the gates of the sun and the -land of dreams, whereon they reached the meadow of asphodel where dwell -the souls and shadows of them that can labour no more. - -Here they found the ghost of Achilles son of Peleus, with those of -Patroclus, Antilochus, and Ajax, who was the finest and handsomest man -of all the Danaans after the son of Peleus himself. - -They gathered round the ghost of the son of Peleus, and the ghost of -Agamemnon joined them, sorrowing bitterly. Round him were gathered also -the ghosts of those who had perished with him in the house of -Aegisthus; and the ghost of Achilles spoke first. - -“Son of Atreus,” it said, “we used to say that Jove had loved you -better from first to last than any other hero, for you were captain -over many and brave men, when we were all fighting together before -Troy; yet the hand of death, which no mortal can escape, was laid upon -you all too early. Better for you had you fallen at Troy in the hey-day -of your renown, for the Achaeans would have built a mound over your -ashes, and your son would have been heir to your good name, whereas it -has now been your lot to come to a most miserable end.” - -“Happy son of Peleus,” answered the ghost of Agamemnon, “for having -died at Troy far from Argos, while the bravest of the Trojans and the -Achaeans fell round you fighting for your body. There you lay in the -whirling clouds of dust, all huge and hugely, heedless now of your -chivalry. We fought the whole of the livelong day, nor should we ever -have left off if Jove had not sent a hurricane to stay us. Then, when -we had borne you to the ships out of the fray, we laid you on your bed -and cleansed your fair skin with warm water and with ointments. The -Danaans tore their hair and wept bitterly round about you. Your mother, -when she heard, came with her immortal nymphs from out of the sea, and -the sound of a great wailing went forth over the waters so that the -Achaeans quaked for fear. They would have fled panic-stricken to their -ships had not wise old Nestor whose counsel was ever truest checked -them saying, ‘Hold, Argives, fly not sons of the Achaeans, this is his -mother coming from the sea with her immortal nymphs to view the body of -her son.’ - -“Thus he spoke, and the Achaeans feared no more. The daughters of the -old man of the sea stood round you weeping bitterly, and clothed you in -immortal raiment. The nine muses also came and lifted up their sweet -voices in lament—calling and answering one another; there was not an -Argive but wept for pity of the dirge they chaunted. Days and nights -seven and ten we mourned you, mortals and immortals, but on the -eighteenth day we gave you to the flames, and many a fat sheep with -many an ox did we slay in sacrifice around you. You were burnt in -raiment of the gods, with rich resins and with honey, while heroes, -horse and foot, clashed their armour round the pile as you were -burning, with the tramp as of a great multitude. But when the flames of -heaven had done their work, we gathered your white bones at daybreak -and laid them in ointments and in pure wine. Your mother brought us a -golden vase to hold them—gift of Bacchus, and work of Vulcan himself; -in this we mingled your bleached bones with those of Patroclus who had -gone before you, and separate we enclosed also those of Antilochus, who -had been closer to you than any other of your comrades now that -Patroclus was no more. - -“Over these the host of the Argives built a noble tomb, on a point -jutting out over the open Hellespont, that it might be seen from far -out upon the sea by those now living and by them that shall be born -hereafter. Your mother begged prizes from the gods, and offered them to -be contended for by the noblest of the Achaeans. You must have been -present at the funeral of many a hero, when the young men gird -themselves and make ready to contend for prizes on the death of some -great chieftain, but you never saw such prizes as silver-footed Thetis -offered in your honour; for the gods loved you well. Thus even in death -your fame, Achilles, has not been lost, and your name lives evermore -among all mankind. But as for me, what solace had I when the days of my -fighting were done? For Jove willed my destruction on my return, by the -hands of Aegisthus and those of my wicked wife.” - -Thus did they converse, and presently Mercury came up to them with the -ghosts of the suitors who had been killed by Ulysses. The ghosts of -Agamemnon and Achilles were astonished at seeing them, and went up to -them at once. The ghost of Agamemnon recognised Amphimedon son of -Melaneus, who lived in Ithaca and had been his host, so it began to -talk to him. - -“Amphimedon,” it said, “what has happened to all you fine young men—all -of an age too—that you are come down here under the ground? One could -pick no finer body of men from any city. Did Neptune raise his winds -and waves against you when you were at sea, or did your enemies make an -end of you on the mainland when you were cattle-lifting or -sheep-stealing, or while fighting in defence of their wives and city? -Answer my question, for I have been your guest. Do you not remember how -I came to your house with Menelaus, to persuade Ulysses to join us with -his ships against Troy? It was a whole month ere we could resume our -voyage, for we had hard work to persuade Ulysses to come with us.” - -And the ghost of Amphimedon answered, “Agamemnon, son of Atreus, king -of men, I remember everything that you have said, and will tell you -fully and accurately about the way in which our end was brought about. -Ulysses had been long gone, and we were courting his wife, who did not -say point blank that she would not marry, nor yet bring matters to an -end, for she meant to compass our destruction: this, then, was the -trick she played us. She set up a great tambour frame in her room and -began to work on an enormous piece of fine needlework. ‘Sweethearts,’ -said she, ‘Ulysses is indeed dead, still, do not press me to marry -again immediately; wait—for I would not have my skill in needlework -perish unrecorded—till I have completed a pall for the hero Laertes, -against the time when death shall take him. He is very rich, and the -women of the place will talk if he is laid out without a pall.’ This is -what she said, and we assented; whereupon we could see her working upon -her great web all day long, but at night she would unpick the stitches -again by torchlight. She fooled us in this way for three years without -our finding it out, but as time wore on and she was now in her fourth -year, in the waning of moons and many days had been accomplished, one -of her maids who knew what she was doing told us, and we caught her in -the act of undoing her work, so she had to finish it whether she would -or no; and when she showed us the robe she had made, after she had had -it washed,186 its splendour was as that of the sun or moon. - -“Then some malicious god conveyed Ulysses to the upland farm where his -swineherd lives. Thither presently came also his son, returning from a -voyage to Pylos, and the two came to the town when they had hatched -their plot for our destruction. Telemachus came first, and then after -him, accompanied by the swineherd, came Ulysses, clad in rags and -leaning on a staff as though he were some miserable old beggar. He came -so unexpectedly that none of us knew him, not even the older ones among -us, and we reviled him and threw things at him. He endured both being -struck and insulted without a word, though he was in his own house; but -when the will of Aegis-bearing Jove inspired him, he and Telemachus -took the armour and hid it in an inner chamber, bolting the doors -behind them. Then he cunningly made his wife offer his bow and a -quantity of iron to be contended for by us ill-fated suitors; and this -was the beginning of our end, for not one of us could string the -bow—nor nearly do so. When it was about to reach the hands of Ulysses, -we all of us shouted out that it should not be given him, no matter -what he might say, but Telemachus insisted on his having it. When he -had got it in his hands he strung it with ease and sent his arrow -through the iron. Then he stood on the floor of the cloister and poured -his arrows on the ground, glaring fiercely about him. First he killed -Antinous, and then, aiming straight before him, he let fly his deadly -darts and they fell thick on one another. It was plain that some one of -the gods was helping them, for they fell upon us with might and main -throughout the cloisters, and there was a hideous sound of groaning as -our brains were being battered in, and the ground seethed with our -blood. This, Agamemnon, is how we came by our end, and our bodies are -lying still uncared for in the house of Ulysses, for our friends at -home do not yet know what has happened, so that they cannot lay us out -and wash the black blood from our wounds, making moan over us according -to the offices due to the departed.” - -“Happy Ulysses, son of Laertes,” replied the ghost of Agamemnon, “you -are indeed blessed in the possession of a wife endowed with such rare -excellence of understanding, and so faithful to her wedded lord as -Penelope the daughter of Icarius. The fame, therefore, of her virtue -shall never die, and the immortals shall compose a song that shall be -welcome to all mankind in honour of the constancy of Penelope. How far -otherwise was the wickedness of the daughter of Tyndareus who killed -her lawful husband; her song shall be hateful among men, for she has -brought disgrace on all womankind even on the good ones.” - -Thus did they converse in the house of Hades deep down within the -bowels of the earth. Meanwhile Ulysses and the others passed out of the -town and soon reached the fair and well-tilled farm of Laertes, which -he had reclaimed with infinite labour. Here was his house, with a -lean-to running all round it, where the slaves who worked for him slept -and sat and ate, while inside the house there was an old Sicel woman, -who looked after him in this his country-farm. When Ulysses got there, -he said to his son and to the other two: - -“Go to the house, and kill the best pig that you can find for dinner. -Meanwhile I want to see whether my father will know me, or fail to -recognise me after so long an absence.” - -He then took off his armour and gave it to Eumaeus and Philoetius, who -went straight on to the house, while he turned off into the vineyard to -make trial of his father. As he went down into the great orchard, he -did not see Dolius, nor any of his sons nor of the other bondsmen, for -they were all gathering thorns to make a fence for the vineyard, at the -place where the old man had told them; he therefore found his father -alone, hoeing a vine. He had on a dirty old shirt, patched and very -shabby; his legs were bound round with thongs of oxhide to save him -from the brambles, and he also wore sleeves of leather; he had a goat -skin cap on his head, and was looking very woe-begone. When Ulysses saw -him so worn, so old and full of sorrow, he stood still under a tall -pear tree and began to weep. He doubted whether to embrace him, kiss -him, and tell him all about his having come home, or whether he should -first question him and see what he would say. In the end he deemed it -best to be crafty with him, so in this mind he went up to his father, -who was bending down and digging about a plant. - -“I see, sir,” said Ulysses, “that you are an excellent gardener—what -pains you take with it, to be sure. There is not a single plant, not a -fig tree, vine, olive, pear, nor flower bed, but bears the trace of -your attention. I trust, however, that you will not be offended if I -say that you take better care of your garden than of yourself. You are -old, unsavoury, and very meanly clad. It cannot be because you are idle -that your master takes such poor care of you, indeed your face and -figure have nothing of the slave about them, and proclaim you of noble -birth. I should have said that you were one of those who should wash -well, eat well, and lie soft at night as old men have a right to do; -but tell me, and tell me true, whose bondman are you, and in whose -garden are you working? Tell me also about another matter. Is this -place that I have come to really Ithaca? I met a man just now who said -so, but he was a dull fellow, and had not the patience to hear my story -out when I was asking him about an old friend of mine, whether he was -still living, or was already dead and in the house of Hades. Believe me -when I tell you that this man came to my house once when I was in my -own country and never yet did any stranger come to me whom I liked -better. He said that his family came from Ithaca and that his father -was Laertes, son of Arceisius. I received him hospitably, making him -welcome to all the abundance of my house, and when he went away I gave -him all customary presents. I gave him seven talents of fine gold, and -a cup of solid silver with flowers chased upon it. I gave him twelve -light cloaks, and as many pieces of tapestry; I also gave him twelve -cloaks of single fold, twelve rugs, twelve fair mantles, and an equal -number of shirts. To all this I added four good looking women skilled -in all useful arts, and I let him take his choice.” - -His father shed tears and answered, “Sir, you have indeed come to the -country that you have named, but it is fallen into the hands of wicked -people. All this wealth of presents has been given to no purpose. If -you could have found your friend here alive in Ithaca, he would have -entertained you hospitably and would have requited your presents amply -when you left him—as would have been only right considering what you -had already given him. But tell me, and tell me true, how many years is -it since you entertained this guest—my unhappy son, as ever was? Alas! -He has perished far from his own country; the fishes of the sea have -eaten him, or he has fallen a prey to the birds and wild beasts of some -continent. Neither his mother, nor I his father, who were his parents, -could throw our arms about him and wrap him in his shroud, nor could -his excellent and richly dowered wife Penelope bewail her husband as -was natural upon his death bed, and close his eyes according to the -offices due to the departed. But now, tell me truly for I want to know. -Who and whence are you—tell me of your town and parents? Where is the -ship lying that has brought you and your men to Ithaca? Or were you a -passenger on some other man’s ship, and those who brought you here have -gone on their way and left you?” - -“I will tell you everything,” answered Ulysses, “quite truly. I come -from Alybas, where I have a fine house. I am son of king Apheidas, who -is the son of Polypemon. My own name is Eperitus; heaven drove me off -my course as I was leaving Sicania, and I have been carried here -against my will. As for my ship it is lying over yonder, off the open -country outside the town, and this is the fifth year since Ulysses left -my country. Poor fellow, yet the omens were good for him when he left -me. The birds all flew on our right hands, and both he and I rejoiced -to see them as we parted, for we had every hope that we should have -another friendly meeting and exchange presents.” - -A dark cloud of sorrow fell upon Laertes as he listened. He filled both -hands with the dust from off the ground and poured it over his grey -head, groaning heavily as he did so. The heart of Ulysses was touched, -and his nostrils quivered as he looked upon his father; then he sprang -towards him, flung his arms about him and kissed him, saying, “I am he, -father, about whom you are asking—I have returned after having been -away for twenty years. But cease your sighing and lamentation—we have -no time to lose, for I should tell you that I have been killing the -suitors in my house, to punish them for their insolence and crimes.” - -“If you really are my son Ulysses,” replied Laertes, “and have come -back again, you must give me such manifest proof of your identity as -shall convince me.” - -“First observe this scar,” answered Ulysses, “which I got from a boar’s -tusk when I was hunting on Mt. Parnassus. You and my mother had sent me -to Autolycus, my mother’s father, to receive the presents which when he -was over here he had promised to give me. Furthermore I will point out -to you the trees in the vineyard which you gave me, and I asked you all -about them as I followed you round the garden. We went over them all, -and you told me their names and what they all were. You gave me -thirteen pear trees, ten apple trees, and forty fig trees; you also -said you would give me fifty rows of vines; there was corn planted -between each row, and they yield grapes of every kind when the heat of -heaven has been laid heavy upon them.” - -Laertes’ strength failed him when he heard the convincing proofs which -his son had given him. He threw his arms about him, and Ulysses had to -support him, or he would have gone off into a swoon; but as soon as he -came to, and was beginning to recover his senses, he said, “O father -Jove, then you gods are still in Olympus after all, if the suitors have -really been punished for their insolence and folly. Nevertheless, I am -much afraid that I shall have all the townspeople of Ithaca up here -directly, and they will be sending messengers everywhere throughout the -cities of the Cephallenians.” - -Ulysses answered, “Take heart and do not trouble yourself about that, -but let us go into the house hard by your garden. I have already told -Telemachus, Philoetius, and Eumaeus to go on there and get dinner ready -as soon as possible.” - -Thus conversing the two made their way towards the house. When they got -there they found Telemachus with the stockman and the swineherd cutting -up meat and mixing wine with water. Then the old Sicel woman took -Laertes inside and washed him and anointed him with oil. She put him on -a good cloak, and Minerva came up to him and gave him a more imposing -presence, making him taller and stouter than before. When he came back -his son was surprised to see him looking so like an immortal, and said -to him, “My dear father, some one of the gods has been making you much -taller and better-looking.” - -Laertes answered, “Would, by Father Jove, Minerva, and Apollo, that I -were the man I was when I ruled among the Cephallenians, and took -Nericum, that strong fortress on the foreland. If I were still what I -then was and had been in our house yesterday with my armour on, I -should have been able to stand by you and help you against the suitors. -I should have killed a great many of them, and you would have rejoiced -to see it.” - -Thus did they converse; but the others, when they had finished their -work and the feast was ready, left off working, and took each his -proper place on the benches and seats. Then they began eating; by and -by old Dolius and his sons left their work and came up, for their -mother, the Sicel woman who looked after Laertes now that he was -growing old, had been to fetch them. When they saw Ulysses and were -certain it was he, they stood there lost in astonishment; but Ulysses -scolded them good naturedly and said, “Sit down to your dinner, old -man, and never mind about your surprise; we have been wanting to begin -for some time and have been waiting for you.” - -Then Dolius put out both his hands and went up to Ulysses. “Sir,” said -he, seizing his master’s hand and kissing it at the wrist, “we have -long been wishing you home: and now heaven has restored you to us after -we had given up hoping. All hail, therefore, and may the gods prosper -you.187 But tell me, does Penelope already know of your return, or -shall we send some one to tell her?” - -“Old man,” answered Ulysses, “she knows already, so you need not -trouble about that.” On this he took his seat, and the sons of Dolius -gathered round Ulysses to give him greeting and embrace him one after -the other; then they took their seats in due order near Dolius their -father. - -While they were thus busy getting their dinner ready, Rumour went round -the town, and noised abroad the terrible fate that had befallen the -suitors; as soon, therefore, as the people heard of it they gathered -from every quarter, groaning and hooting before the house of Ulysses. -They took the dead away, buried every man his own, and put the bodies -of those who came from elsewhere on board the fishing vessels, for the -fishermen to take each of them to his own place. They then met angrily -in the place of assembly, and when they were got together Eupeithes -rose to speak. He was overwhelmed with grief for the death of his son -Antinous, who had been the first man killed by Ulysses, so he said, -weeping bitterly, “My friends, this man has done the Achaeans great -wrong. He took many of our best men away with him in his fleet, and he -has lost both ships and men; now, moreover, on his return he has been -killing all the foremost men among the Cephallenians. Let us be up and -doing before he can get away to Pylos or to Elis where the Epeans rule, -or we shall be ashamed of ourselves for ever afterwards. It will be an -everlasting disgrace to us if we do not avenge the murder of our sons -and brothers. For my own part I should have no more pleasure in life, -but had rather die at once. Let us be up, then, and after them, before -they can cross over to the main land.” - -He wept as he spoke and every one pitied him. But Medon and the bard -Phemius had now woke up, and came to them from the house of Ulysses. -Every one was astonished at seeing them, but they stood in the middle -of the assembly, and Medon said, “Hear me, men of Ithaca. Ulysses did -not do these things against the will of heaven. I myself saw an -immortal god take the form of Mentor and stand beside him. This god -appeared, now in front of him encouraging him, and now going furiously -about the court and attacking the suitors whereon they fell thick on -one another.” - -On this pale fear laid hold of them, and old Halitherses, son of -Mastor, rose to speak, for he was the only man among them who knew both -past and future; so he spoke to them plainly and in all honesty, -saying, - -“Men of Ithaca, it is all your own fault that things have turned out as -they have; you would not listen to me, nor yet to Mentor, when we bade -you check the folly of your sons who were doing much wrong in the -wantonness of their hearts—wasting the substance and dishonouring the -wife of a chieftain who they thought would not return. Now, however, -let it be as I say, and do as I tell you. Do not go out against -Ulysses, or you may find that you have been drawing down evil on your -own heads.” - -This was what he said, and more than half raised a loud shout, and at -once left the assembly. But the rest stayed where they were, for the -speech of Halitherses displeased them, and they sided with Eupeithes; -they therefore hurried off for their armour, and when they had armed -themselves, they met together in front of the city, and Eupeithes led -them on in their folly. He thought he was going to avenge the murder of -his son, whereas in truth he was never to return, but was himself to -perish in his attempt. - -Then Minerva said to Jove, “Father, son of Saturn, king of kings, -answer me this question—What do you propose to do? Will you set them -fighting still further, or will you make peace between them?” - -And Jove answered, “My child, why should you ask me? Was it not by your -own arrangement that Ulysses came home and took his revenge upon the -suitors? Do whatever you like, but I will tell you what I think will be -most reasonable arrangement. Now that Ulysses is revenged, let them -swear to a solemn covenant, in virtue of which he shall continue to -rule, while we cause the others to forgive and forget the massacre of -their sons and brothers. Let them then all become friends as -heretofore, and let peace and plenty reign.” - -This was what Minerva was already eager to bring about, so down she -darted from off the topmost summits of Olympus. - -Now when Laertes and the others had done dinner, Ulysses began by -saying, “Some of you go out and see if they are not getting close up to -us.” So one of Dolius’s sons went as he was bid. Standing on the -threshold he could see them all quite near, and said to Ulysses, “Here -they are, let us put on our armour at once.” - -They put on their armour as fast as they could—that is to say Ulysses, -his three men, and the six sons of Dolius. Laertes also and Dolius did -the same—warriors by necessity in spite of their grey hair. When they -had all put on their armour, they opened the gate and sallied forth, -Ulysses leading the way. - -Then Jove’s daughter Minerva came up to them, having assumed the form -and voice of Mentor. Ulysses was glad when he saw her, and said to his -son Telemachus, “Telemachus, now that you are about to fight in an -engagement, which will show every man’s mettle, be sure not to disgrace -your ancestors, who were eminent for their strength and courage all the -world over.” - -“You say truly, my dear father,” answered Telemachus, “and you shall -see, if you will, that I am in no mind to disgrace your family.” - -Laertes was delighted when he heard this. “Good heavens,” he exclaimed, -“what a day I am enjoying: I do indeed rejoice at it. My son and -grandson are vying with one another in the matter of valour.” - -On this Minerva came close up to him and said, “Son of Arceisius—-best -friend I have in the world—pray to the blue-eyed damsel, and to Jove -her father; then poise your spear and hurl it.” - -As she spoke she infused fresh vigour into him, and when he had prayed -to her he poised his spear and hurled it. He hit Eupeithes’ helmet, and -the spear went right through it, for the helmet stayed it not, and his -armour rang rattling round him as he fell heavily to the ground. -Meantime Ulysses and his son fell upon the front line of the foe and -smote them with their swords and spears; indeed, they would have killed -every one of them, and prevented them from ever getting home again, -only Minerva raised her voice aloud, and made every one pause. “Men of -Ithaca,” she cried, “cease this dreadful war, and settle the matter at -once without further bloodshed.” - -On this pale fear seized every one; they were so frightened that their -arms dropped from their hands and fell upon the ground at the sound of -the goddess’ voice, and they fled back to the city for their lives. But -Ulysses gave a great cry, and gathering himself together swooped down -like a soaring eagle. Then the son of Saturn sent a thunderbolt of fire -that fell just in front of Minerva, so she said to Ulysses, “Ulysses, -noble son of Laertes, stop this warful strife, or Jove will be angry -with you.” - -Thus spoke Minerva, and Ulysses obeyed her gladly. Then Minerva assumed -the form and voice of Mentor, and presently made a covenant of peace -between the two contending parties. - - - - -FOOTNOTES: - -[1] [ Black races are evidently known to the writer as stretching all -across Africa, one half looking West on to the Atlantic, and the other -East on to the Indian Ocean.] - -[2] [ The original use of the footstool was probably less to rest the -feet than to keep them (especially when bare) from a floor which was -often wet and dirty.] - -[3] [ The θρόνος or seat, is occasionally called “high,” as being -higher than the θρῆνυς or low footstool. It was probably no higher than -an ordinary chair is now, and seems to have had no back.] - -[4] [ Temesa was on the West Coast of the toe of Italy, in what is now -the gulf of Sta Eufemia. It was famous in remote times for its copper -mines, which, however, were worked out when Strabo wrote.] - -[5] [ i.e. “with a current in it”—see illustrations and map near the -end of bks. v. and vi. respectively.] - -[6] [ Reading Νηρίτῳ for Νηίῳ, cf. “Od.” iii. 81 where the same mistake -is made, and xiii. 351 where the mountain is called Neritum, the same -place being intended both here and in book xiii.] - -[7] [ It is never plausibly explained why Penelope cannot do this, and -from bk. ii. it is clear that she kept on deliberately encouraging the -suitors, though we are asked to believe that she was only fooling -them.] - -[8] [ See note on “Od.” i. 365.] - -[9] [ Middle Argos means the Peleponnese which, however, is never so -called in the “Iliad”. I presume “middle” means “middle between the two -Greek-speaking countries of Asia Minor and Sicily, with South Italy”; -for that parts of Sicily and also large parts, though not the whole of -South Italy, were inhabited by Greek-speaking races centuries before -the Dorian colonisations can hardly be doubted. The Sicians, and also -the Sicels, both of them probably spoke Greek.] - -[10] [ cf. “Il.” vi. 490-495. In the “Iliad” it is “war,” not “speech,” -that is a man’s matter. It argues a certain hardness, or at any rate -dislike of the “Iliad” on the part of the writer of the “Odyssey,” that -she should have adopted Hector’s farewell to Andromache here, as -elsewhere in the poem, for a scene of such inferior pathos.] - -[11] [ μέγαρα σκιοέντα The whole open court with the covered cloister -running round it was called μέγαρον, or μέγαρα, but the covered part -was distinguished by being called “shady” or “shadow-giving”. It was in -this part that the tables for the suitors were laid. The Fountain Court -at Hampton Court may serve as an illustration (save as regards the use -of arches instead of wooden supports and rafters) and the arrangement -is still common in Sicily. The usual translation “shadowy” or “dusky” -halls, gives a false idea of the scene.] - -[12] [ The reader will note the extreme care which the writer takes to -make it clear that none of the suitors were allowed to sleep in -Ulysses’ house.] - -[13] [ See Appendix; g, in plan of Ulysses’ house.] - -[14] [ I imagine this passage to be a rejoinder to “Il.” xxiii. 702-705 -in which a tripod is valued at twelve oxen, and a good useful maid of -all work at only four. The scrupulous regard of Laertes for his wife’s -feelings is of a piece with the extreme jealousy for the honour of -woman, which is manifest throughout the “Odyssey”.] - -[15] [ χιτῶνα “The χιτών, or _tunica_, was a shirt or shift, and served -as the chief under garment of the Greeks and Romans, whether men or -women.” Smith’s Dictionary of Greek and Roman Antiquities, under -“Tunica”.] - -[16] [ Doors fastened to all intents and purposes as here described may -be seen in the older houses at Trapani. There is a slot on the outer -side of the door by means of which a person who has left the room can -shoot the bolt. My bedroom at the Albergo Centrale was fastened in this -way.] - -[17] [ πύματον δ’ ὡπλίσσατο δόρπον. So we vulgarly say “had cooked his -goose,” or “had settled his hash.” Ægyptius cannot of course know of -the fate Antiphus had met with, for there had as yet been no news of or -from Ulysses.] - -[18] [ “Il.” xxii. 416. σχέσθε φίλοι, καὶ μ’ οἷον ἐάσατε...... The -authoress has bungled by borrowing these words verbatim from the -“Iliad”, without prefixing the necessary “do not,” which I have -supplied.] - -[19] [ i.e. you have money, and could pay when I got judgment, whereas -the suitors are men of straw.] - -[20] [ cf. “Il.” ii. 76. ἦ τοι ὄ γ’ ὦς εὶπὼν κατ’ ἄρ’ ἔζετο τοῖσι δ’ -ἀνέστη -Νέστωρ, ὄς ῥα....................................... -ὄ σφιν ἐὺ φρονέων ἀγορήσατο καὶ μετέειπεν. -The Odyssean passage runs— -“ἦ τοι ὄ γ’ ὦς εὶπὼν κατ’ ἄρ’ ἔζετο τοῖσι δ’ ἀνέστη -Μεντορ ὄς ῥ’....................................... -ὄ σφιν ἐὺ φρονέων ἀγορήσατο καὶ μετέειπεν. -Is it possible not to suspect that the name Mentor was coined upon that -of Nestor?] - -[21] [ i.e. in the outer court, and in the uncovered part of the inner -house.] - -[22] [ This would be fair from Sicily, which was doing duty for Ithaca -in the mind of the writer, but a North wind would have been preferable -for a voyage from the real Ithaca to Pylos.] - -[23] [ κελάδοντ’ ἐπὶ οὶνοπα πόντον The wind does not whistle over -waves. It only whistles through rigging or some other obstacle that -cuts it.] - -[24] [ cf. “Il.” v.20. Ἰδαῖος δ’ ἀπόρουσε λιπὼν περικαλλέα δίφρον, the -Odyssean line is ἠέλιος δ’ ἀνόρουσε λιπὼν περικαλλέα λίμνην. There can -be no doubt that the Odyssean line was suggested by the Iliadic, but -nothing can explain why Idæus jumping from his chariot should suggest -to the writer of the “Odyssey” the sun jumping from the sea. The -probability is that she never gave the matter a thought, but took the -line in question as an effect of saturation with the “Iliad,” and of -unconscious cerebration. The “Odyssey” contains many such examples.] - -[25] [ The heart, liver, lights, kidneys, etc. were taken out from the -inside and eaten first as being more readily cooked; the {Greek}, or -bone meat, was cooking while the {Greek} or inward parts were being -eaten. I imagine that the thigh bones made a kind of gridiron, while at -the same time the marrow inside them got cooked.] - -[26] [ i.e. skewers, either single, double, or even five pronged. The -meat would be pierced with the skewer, and laid over the ashes to -grill—the two ends of the skewer being supported in whatever way -convenient. Meat so cooking may be seen in any eating house in Smyrna, -or any Eastern town. When I rode across the Troad from the Dardanelles -to Hissarlik and Mount Ida, I noticed that my dragoman and his men did -all our outdoor cooking exactly in the Odyssean and Iliadic fashion.] - -[27] [ cf. “Il.” xvii. 567. {Greek} The Odyssean lines are—{Greek}] - -[28] [ Reading {Greek} for {Greek}, cf. “Od.” i. 186.] - -29[] [ The geography of the Ægean as above described is correct, but is -probably taken from the lost poem, the Nosti, the existence of which is -referred to “Od.” i. 326, 327 and 350, &c. A glance at the map will -show that heaven advised its supplicants quite correctly.] - -[30] [ The writer—ever jealous for the honour of women—extenuates -Clytemnestra’s guilt as far as possible, and explains it as due to her -having been left unprotected, and fallen into the hands of a wicked -man.] - -[31] [ The Greek is {Greek} cf. “Iliad” ii. 408 {Greek} Surely the -{Greek} of the Odyssean passage was due to the {Greek} of the “Iliad.” -No other reason suggests itself for the making Menelaus return on the -very day of the feast given by Orestes. The fact that in the “Iliad” -Menelaus came to a banquet without waiting for an invitation, -determines the writer of the “Odyssey” to make him come to a banquet, -also uninvited, but as circumstances did not permit of his having been -invited, his coming uninvited is shown to have been due to chance. I do -not think the authoress thought all this out, but attribute the -strangeness of the coincidence to unconscious cerebration and -saturation.] - -[32] [ cf. “Il.” I. 458, II. 421. The writer here interrupts an Iliadic -passage (to which she returns immediately) for the double purpose of -dwelling upon the slaughter of the heifer, and of letting Nestor’s wife -and daughter enjoy it also. A male writer, if he was borrowing from the -“Iliad,” would have stuck to his borrowing.] - -[33] [ cf. “Il.” xxiv. 587, 588 where the lines refer to the washing -the dead body of Hector.] - -[34] [ See illustration on opposite page. The yard is typical of many -that may be seen in Sicily. The existing ground-plan is probably -unmodified from Odyssean, and indeed long pre-Odyssean times, but the -earlier buildings would have no arches, and would, one would suppose, -be mainly timber. The Odyssean {Greek} were the sheds that ran round -the yard as the arches do now. The {Greek} was the one through which -the main entrance passed, and which was hence “noisy,” or -reverberating. It had an upper story in which visitors were often -lodged.] - -[35] [ This journey is an impossible one. Telemachus and Pisistratus -would have been obliged to drive over the Taygetus range, over which -there has never yet been a road for wheeled vehicles. It is plain -therefore that the audience for whom the “Odyssey” was written was one -that would be unlikely to know anything about the topography of the -Peloponnese, so that the writer might take what liberties she chose.] - -[36] [ The lines which I have enclosed in brackets are evidently an -afterthought—added probably by the writer herself—for they evince the -same instinctively greater interest in anything that may concern a -woman, which is so noticeable throughout the poem. There is no further -sign of any special festivities nor of any other guests than Telemachus -and Pisistratus, until lines 621-624 (ordinarily enclosed in brackets) -are abruptly introduced, probably with a view of trying to carry off -the introduction of the lines now in question. - -The addition was, I imagine, suggested by a desire to excuse and -explain the non-appearance of Hermione in bk. xv., as also of both -Hermione and Megapenthes in the rest of bk. iv. Megapenthes in bk. xv. -seems to be still a bachelor: the presumption therefore is that bk. xv. -was written before the story of his marriage here given. I take it he -is only married here because his sister is being married. She having -been properly attended to, Megapenthes might as well be married at the -same time. Hermione could not now be less than thirty. - -I have dealt with this passage somewhat more fully in my “Authoress of -the Odyssey”, p. 136-138. See also p. 256 of the same book.] - -[37] [ Sparta and Lacedaemon are here treated as two different places, -though in other parts of the poem it is clear that the writer -understands them as one. The catalogue in the “Iliad,” which the writer -is here presumably following, makes the same mistake (“Il.” ii. 581, -582)] - -[38] [ These last three lines are identical with “Il.” vxiii. 604-606.] - -[39] [ From the Greek {Greek} it is plain that Menelaus took up the -piece of meat with his fingers.] - -[40] [ Amber is never mentioned in the “Iliad.” Sicily, where I suppose -the “Odyssey” to have been written, has always been, and still is, one -of the principal amber producing countries. It was probably the only -one known in the Odyssean age. See “The Authoress of the Odyssey,” -Longmans 1898, p. 186.] - -[41] [ This no doubt refers to the story told in the last poem of the -Cypria about Paris and Helen robbing Menelaus of the greater part of -his treasures, when they sailed together for Troy.] - -[42] [ It is inconceivable that Helen should enter thus, in the middle -of supper, intending to work with her distaff, if great festivities -were going on. Telemachus and Pisistratus are evidently dining en -famille.] - -[43] [ In the Italian insurrection of 1848, eight young men who were -being hotly pursued by the Austrian police hid themselves inside -Donatello’s colossal wooden horse in the Salone at Padua, and remained -there for a week being fed by their confederates. In 1898 the last -survivor was carried round Padua in triumph.] - -[44] [ The Greek is {Greek}. Is it unfair to argue that the writer is a -person of somewhat delicate sensibility, to whom a strong smell of fish -is distasteful?] - -[45] [ The Greek is {Greek}. I believe this to be a hit at the writer’s -own countrymen who were of Phocaean descent, and the next following -line to be a rejoinder to complaints made against her in bk. vi. -273-288, to the effect that she gave herself airs and would marry none -of her own people. For that the writer of the “Odyssey” was the person -who has been introduced into the poem under the name of Nausicaa, I -cannot bring myself to question. I may remind English readers that -{Greek} (i.e. phoca) means “seal.” Seals almost always appear on -Phocaean coins.] - -[46] [ Surely here again we are in the hands of a writer of delicate -sensibility. It is not as though the seals were stale; they had only -just been killed. The writer, however is obviously laughing at her own -countrymen, and insulting them as openly as she dares.] - -[47] [ We were told above (lines 356, 357) that it was only one day’s -sail.] - -[48] [ I give the usual translation, but I do not believe the Greek -will warrant it. The Greek reads {Greek}. - -This is usually held to mean that Ithaca is an island fit for breeding -goats, and on that account more delectable to the speaker than it would -have been if it were fit for breeding horses. I find little authority -for such a translation; the most equitable translation of the text as -it stands is, “Ithaca is an island fit for breeding goats, and -delectable rather than fit for breeding horses; for not one of the -islands is good driving ground, nor well meadowed.” Surely the writer -does not mean that a pleasant or delectable island would not be fit for -breeding horses? The most equitable translation, therefore, of the -present text being thus halt and impotent, we may suspect corruption, -and I hazard the following emendation, though I have not adopted it in -my translation, as fearing that it would be deemed too fanciful. I -would read:—{Greek}. - -As far as scanning goes the {Greek} is not necessary; {Greek} iv. 72, -(Footnote Greek) iv. 233, to go no further afield than earlier lines of -the same book, give sufficient authority for {Greek}, but the {Greek} -would not be redundant; it would emphasise the surprise of the -contrast, and I should prefer to have it, though it is not very -important either way. This reading of course should be translated -“Ithaca is an island fit for breeding goats, and (by your leave) itself -a horseman rather than fit for breeding horses—for not one of the -islands is good and well meadowed ground.” - -This would be sure to baffle the Alexandrian editors. “How,” they would -ask themselves, “could an island be a horseman?” and they would cast -about for an emendation. A visit to the top of Mt. Eryx might perhaps -make the meaning intelligible, and suggest my proposed restoration of -the text to the reader as readily as it did to myself. - -I have elsewhere stated my conviction that the writer of the “Odyssey” -was familiar with the old Sican city at the top of Mt. Eryx, and that -the Aegadean islands which are so striking when seen thence did duty -with her for the Ionian islands—Marettimo, the highest and most -westerly of the group, standing for Ithaca. When seen from the top of -Mt. Eryx Marettimo shows as it should do according to “Od.” ix. 25, 26, -“on the horizon, all highest up in the sea towards the West,” while the -other islands lie “some way off it to the East.” As we descend to -Trapani, Marettimo appears to sink on to the top of the island of -Levanzo, behind which it disappears. My friend, the late Signor E. -Biaggini, pointed to it once as it was just standing on the top of -Levanzo, and said to me “Come cavalca bene” (“How well it rides”), and -this immediately suggested my emendation to me. Later on I found in the -hymn to the Pythian Apollo (which abounds with tags taken from the -“Odyssey”) a line ending {Greek} which strengthened my suspicion that -this was the original ending of the second of the two lines above under -consideration.] - -[49] [ See note on line 3 of this book. The reader will observe that -the writer has been unable to keep the women out of an interpolation -consisting only of four lines.] - -[50] [ Scheria means a piece of land jutting out into the sea. In my -“Authoress of the Odyssey” I thought “Jutland” would be a suitable -translation, but it has been pointed out to me that “Jutland” only -means the land of the Jutes.] - -[51] [ Irrigation as here described is common in gardens near Trapani. -The water that supplies the ducts is drawn from wells by a mule who -turns a wheel with buckets on it.] - -[52] [ There is not a word here about the cattle of the sun-god.] - -[53] [ The writer evidently thought that green, growing wood might also -be well seasoned.] - -[54] [ The reader will note that the river was flowing with salt water -i.e. that it was tidal.] - -[55] [ Then the Ogygian island was not so far off, but that Nausicaa -might be assumed to know where it was.] - -[56] [ Greek {Greek}] - -[57] [ I suspect a family joke, or sly allusion to some thing of which -we know nothing, in this story of Eurymedusa’s having been brought from -Apeira. The Greek word “apeiros” means “inexperienced,” “ignorant.” Is -it possible that Eurymedusa was notoriously incompetent?] - -[58] [ Polyphemus was also son to Neptune, see “Od.” ix. 412, 529. he -was therefore half brother to Nausithous, half uncle to King Alcinous, -and half great uncle to Nausicaa.] - -[59] [ It would seem as though the writer thought that Marathon was -close to Athens.] - -[60] [ Here the writer, knowing that she is drawing (with -embellishments) from things actually existing, becomes impatient of -past tenses and slides into the present.] - -[61] [ This is hidden malice, implying that the Phaeacian magnates were -no better than they should be. The final drink-offering should have -been made to Jove or Neptune, not to the god of thievishness and -rascality of all kinds. In line 164 we do indeed find Echeneus -proposing that a drink-offering should be made to Jove, but Mercury is -evidently, according to our authoress, the god who was most likely to -be of use to them.] - -[62] [ The fact of Alcinous knowing anything about the Cyclopes -suggests that in the writer’s mind Scheria and the country of the -Cyclopes were not very far from one another. I take the Cyclopes and -the giants to be one and the same people.] - -[63] [ “My property, etc.” The authoress is here adopting an Iliadic -line (xix. 333), and this must account for the absence of all reference -to Penelope. If she had happened to remember “Il.” v. 213, she would -doubtless have appropriated it by preference, for that line reads “my -country, _my wife_, and all the greatness of my house.”] - -[64] [ The at first inexplicable sleep of Ulysses (bk. xiii. 79, etc.) -is here, as also in viii. 445, being obviously prepared. The writer -evidently attached the utmost importance to it. Those who know that the -harbour which did duty with the writer of the “Odyssey” for the one in -which Ulysses landed in Ithaca, was only about 2 miles from the place -in which Ulysses is now talking with Alcinous, will understand why the -sleep was so necessary.] - -[65] [ There were two classes—the lower who were found in provisions -which they had to cook for themselves in the yards and outer precincts, -where they would also eat—and the upper who would eat in the cloisters -of the inner court, and have their cooking done for them.] - -[66] [ Translation very dubious. I suppose the {Greek} here to be the -covered sheds that ran round the outer courtyard. See illustrations at -the end of bk. iii.] - -[67] [ The writer apparently deems that the words “as compared with -what oxen can plough in the same time” go without saying. Not so the -writer of the “Iliad” from which the Odyssean passage is probably -taken. He explains that mules can plough quicker than oxen (“Il.” x. -351-353)] - -[68] [ It was very fortunate that such a disc happened to be there, -seeing that none like it were in common use.] - -[69] [ “Il.” xiii. 37. Here, as so often elsewhere in the “Odyssey,” -the appropriation of an Iliadic line which is not quite appropriate -puzzles the reader. The “they” is not the chains, nor yet Mars and -Venus. It is an overflow from the Iliadic passage in which Neptune -hobbles his horses in bonds “which none could either unloose or break -so that they might stay there in that place.” If the line would have -scanned without the addition of the words “so that they might stay -there in that place,” they would have been omitted in the “Odyssey.”] - -[70] [ The reader will note that Alcinous never goes beyond saying that -he is going to give the goblet; he never gives it. Elsewhere in both -“Iliad” and “Odyssey” the offer of a present is immediately followed by -the statement that it was given and received gladly—Alcinous actually -does give a chest and a cloak and shirt—probably also some of the corn -and wine for the long two-mile voyage was provided by him—but it is -quite plain that he gave no talent and no cup.] - -[71] [ “Il.” xviii. 344-349. These lines in the “Iliad” tell of the -preparation for washing the body of Patroclus, and I am not pleased -that the writer of the “Odyssey” should have adopted them here.] - -[72] [ see note [64] : ] - -[73] [ see note [43] : ] - -[74] [ The reader will find this threat fulfilled in bk. xiii] - -[75] [ If the other islands lay some distance away from Ithaca (which -the word {Greek} suggests), what becomes of the πόρθμος or gut between -Ithaca and Samos which we hear of in Bks. iv. and xv.? I suspect that -the authoress in her mind makes Telemachus come back from Pylos to the -Lilybaean promontory and thence to Trapani through the strait between -the _Isola Grande_ and the mainland—the island of Asteria being the one -on which Motya afterwards stood.] - -[76] [ “Il.” xviii. 533-534. The sudden lapse into the third person -here for a couple of lines is due to the fact that the two Iliadic -lines taken are in the third person.] - -[77] [ cf. “Il.” ii. 776. The words in both “Iliad” and “Odyssey” are -[Footnote Greek]. In the “Iliad” they are used of the horses of -Achilles’ followers as they stood idle, “champing lotus.”] - -[78] [ I take all this passage about the Cyclopes having no ships to be -sarcastic—meaning, “You people of Drepanum have no excuse for not -colonising the island of Favognana, which you could easily do, for you -have plenty of ships, and the island is a very good one.” For that the -island so fully described here is the Aegadean or “goat” island of -Favognana, and that the Cyclopes are the old Sican inhabitants of Mt. -Eryx should not be doubted.] - -[79] [ For the reasons why it was necessary that the night should be so -exceptionally dark see “The Authoress of the Odyssey” pp. 188-189.] - -[80] [ None but such lambs as would suck if they were with their -mothers would be left in the yard. The older lambs should have been out -feeding. The authoress has got it all wrong, but it does not matter. -See “The Authoress of the Odyssey” p. 148.] - -[81] [ This line is enclosed in brackets in the received text, and is -omitted (with note) by Messrs. Butcher & Lang. But lines enclosed in -brackets are almost always genuine; all that brackets mean is that the -bracketed passage puzzled some early editor, who nevertheless found it -too well established in the text to venture on omitting it. In the -present case the line bracketed is the very last which a full-grown -male editor would be likely to interpolate. It is safer to infer that -the writer, a young woman, not knowing or caring at which end of the -ship the rudder should be, determined to make sure by placing it at -both ends, which we shall find she presently does by repeating it (line -340) at the stern of the ship. As for the two rocks thrown, the first I -take to be the Asinelli, see map facing p. 80. The second I see as the -two contiguous islands of the Formiche, which are treated as one, see -map facing p. 108. The Asinelli is an island shaped like a boat, and -pointing to the island of Favognana. I think the authoress’s -compatriots, who probably did not like her much better that she did -them, jeered at the absurdity of Ulysses’ conduct, and saw the Asinelli -or “donkeys,” not as the rock thrown by Polyphemus, but as the boat -itself containing Ulysses and his men.] - -[82] [ This line exists in the text here but not in the corresponding -passage xii. 141. I am inclined to think it is interpolated (probably -by the poetess herself) from the first of lines xi. 115-137, which I -can hardly doubt were added by the writer when the scheme of the work -was enlarged and altered. See “The Authoress of the Odyssey” pp. -254-255.] - -[83] [ “Floating” (πλωτῇ) is not to be taken literally. The island -itself, as apart from its inhabitants, was quite normal. There is no -indication of its moving during the month that Ulysses stayed with -Aeolus, and on his return from his unfortunate voyage, he seems to have -found it in the same place. The πλωτῇ in fact should no more be pressed -than θοῇσι as applied to islands, “Odyssey” xv. 299—where they are -called “flying” because the ship would fly past them. So also the -“Wanderers,” as explained by Buttmann; see note on “Odyssey” xii. 57.] - -[84] [ Literally “for the ways of the night and of the day are near.” I -have seen what Mr. Andrew Lang says (“Homer and the Epic,” p. 236, and -“Longman’s Magazine” for January, 1898, p. 277) about the “amber route” -and the “Sacred Way” in this connection; but until he gives his grounds -for holding that the Mediterranean peoples in the Odyssean age used to -go far North for their amber instead of getting it in Sicily, where it -is still found in considerable quantities, I do not know what weight I -ought to attach to his opinion. I have been unable to find grounds for -asserting that B.C. 1000 there was any commerce between the -Mediterranean and the “Far North,” but I shall be very ready to learn -if Mr. Lang will enlighten me. See “The Authoress of the Odyssey” pp. -185-186.] - -[85] [ One would have thought that when the sun was driving the stag -down to the water, Ulysses might have observed its whereabouts.] - -[86] [ See Hobbes of Malmesbury’s translation.] - -[87] [ “Il.” vxiii. 349. Again the writer draws from the washing the -body of Patroclus—which offends.] - -[88] [ This visit is wholly without topographical significance.] - -[89] [ Brides presented themselves instinctively to the imagination of -the writer, as the phase of humanity which she found most interesting.] - -[90] [ Ulysses was, in fact, to become a missionary and preach Neptune -to people who knew not his name. I was fortunate enough to meet in -Sicily a woman carrying one of these winnowing shovels; it was not much -shorter than an oar, and I was able at once to see what the writer of -the “Odyssey” intended.] - -[91] [ I suppose the lines I have enclosed in brackets to have been -added by the author when she enlarged her original scheme by the -addition of books i.-iv. and xiii. (from line 187)-xxiv. The reader -will observe that in the corresponding passage (xii. 137-141) the -prophecy ends with “after losing all your comrades,” and that there is -no allusion to the suitors. For fuller explanation see “The Authoress -of the Odyssey” pp. 254-255.] - -[92] [ The reader will remember that we are in the first year of -Ulysses’ wanderings, Telemachus therefore was only eleven years old. -The same anachronism is made later on in this book. See “The Authoress -of the Odyssey” pp. 132-133.] - -[93] [ Tradition says that she had hanged herself. Cf. “Odyssey” xv. -355, etc.] - -[94] [ Not to be confounded with Aeolus king of the winds.] - -[95] [ Melampus, vide book xv. 223, etc.] - -[96] [ I have already said in a note on bk. xi. 186 that at this point -of Ulysses’ voyage Telemachus could only be between eleven and twelve -years old.] - -[97] [ Is the writer a man or a woman?] - -[98] [ Cf. “Il.” iv. 521, {Greek}. The Odyssean line reads, {Greek}. -The famous dactylism, therefore, of the Odyssean line was probably -suggested by that of the Ileadic rather than by a desire to accommodate -sound to sense. At any rate the double coincidence of a dactylic line, -and an ending {Greek}, seems conclusive as to the familiarity of the -writer of the “Odyssey” with the Iliadic line.] - -[99] [ Off the coast of Sicily and South Italy, in the month of May, I -have seen men fastened half way up a boat’s mast with their feet -resting on a crosspiece, just large enough to support them. From this -point of vantage they spear sword-fish. When I saw men thus employed I -could hardly doubt that the writer of the “Odyssey” had seen others -like them, and had them in her mind when describing the binding of -Ulysses. I have therefore with some diffidence ventured to depart from -the received translation of ἰστοπέδη (cf. Alcaeus frag. 18, where, -however, it is very hard to say what ἰστοπέδαν means). In Sophocles’ -Lexicon I find a reference to Chrysostom (l, 242, A. Ed. Benedictine -Paris 1834-1839) for the word ἰστοπόδη, which is probably the same as -ἰστοπέδη, but I have looked for the passage in vain.] - -[100] [ The writer is at fault here and tries to put it off on Circe. -When Ulysses comes to take the route prescribed by Circe, he ought to -pass either the Wanderers or some other difficulty of which we are not -told, but he does not do so. The Planctae, or Wanderers, merge into -Scylla and Charybdis, and the alternative between them and something -untold merges into the alternative whether Ulysses had better choose -Scylla or Charybdis. Yet from line 260, it seems we are to consider the -Wanderers as having been passed by Ulysses; this appears even more -plainly from xxiii. 327, in which Ulysses expressly mentions the -Wandering rocks as having been between the Sirens and Scylla and -Charybdis. The writer, however, is evidently unaware that she does not -quite understand her own story; her difficulty was perhaps due to the -fact that though Trapanese sailors had given her a fair idea as to -where all her other localities really were, no one in those days more -than in our own could localise the Planctae, which in fact, as Buttmann -has argued, were derived not from any particular spot, but from -sailors’ tales about the difficulties of navigating the group of the -Aeolian islands as a whole (see note on “Od.” x. 3). Still the matter -of the poor doves caught her fancy, so she would not forgo them. The -whirlwinds of fire and the smoke that hangs on Scylla suggests allusion -to Stromboli and perhaps even Etna. Scylla is on the Italian side, and -therefore may be said to look West. It is about 8 miles thence to the -Sicilian coast, so Ulysses may be perfectly well told that after -passing Scylla he will come to the Thrinacian island or Sicily. -Charybdis is transposed to a site some few miles to the north of its -actual position.] - -[101] [ I suppose this line to have been intercalated by the author -when lines 426-446 were added.] - -[102] [ For the reasons which enable us to identify the island of the -two Sirens with the Lipari island now Salinas—the ancient Didyme, or -“twin” island—see The Authoress of the Odyssey, pp. 195, 196. The two -Sirens doubtless were, as their name suggests, the whistling gusts, or -avalanches of air that at times descend without a moment’s warning from -the two lofty mountains of Salinas—as also from all high points in the -neighbourhood.] - -[103] [ See Admiral Smyth on the currents in the Straits of Messina, -quoted in “The Authoress of the Odyssey,” p. 197.] - -[104] [ In the islands of Favognana and Marettimo off Trapani I have -seen men fish exactly as here described. They chew bread into a paste -and throw it into the sea to attract the fish, which they then spear. -No line is used.] - -[105] [ The writer evidently regards Ulysses as on a coast that looked -East at no great distance south of the Straits of Messina somewhere, -say, near Tauromenium, now Taormina.] - -[106] [ Surely there must be a line missing here to tell us that the -keel and mast were carried down into Charybdis. Besides, the aorist -{Greek} in its present surrounding is perplexing. I have translated it -as though it were an imperfect; I see Messrs. Butcher and Lang -translate it as a pluperfect, but surely Charybdis was in the act of -sucking down the water when Ulysses arrived.] - -[107] [ I suppose the passage within brackets to have been an -afterthought but to have been written by the same hand as the rest of -the poem. I suppose xii. 103 to have been also added by the writer when -she decided on sending Ulysses back to Charybdis. The simile suggests -the hand of the wife or daughter of a magistrate who had often seen her -father come in cross and tired.] - -[108] [ Gr. πολυδαίδαλος. This puts coined money out of the question, -but nevertheless implies that the gold had been worked into ornaments -of some kind.] - -[109] [ I suppose Teiresias’ prophecy of bk. xi. 114-120 had made no -impression on Ulysses. More probably the prophecy was an afterthought, -intercalated, as I have already said, by the authoress when she changed -her scheme.] - -[110] [ A male writer would have made Ulysses say, not “may you give -satisfaction to your wives,” but “may your wives give satisfaction to -you.”] - -[111] [ See note [64].] - -[112] [ The land was in reality the shallow inlet, now the salt works -of S. Cusumano—the neighbourhood of Trapani and Mt. Eryx being made to -do double duty, both as Scheria and Ithaca. Hence the necessity for -making Ulysses set out after dark, fall instantly into a profound -sleep, and wake up on a morning so foggy that he could not see anything -till the interviews between Neptune and Jove and between Ulysses and -Minerva should have given the audience time to accept the situation. -See illustrations and map near the end of bks. v. and vi. -respectively.] - -[113] [ This cave, which is identifiable with singular completeness, is -now called the “grotta del toro,” probably a corruption of “tesoro,” -for it is held to contain a treasure. See The Authoress of the Odyssey, -pp. 167-170.] - -[114] [ Probably they would.] - -[115] [ Then it had a shallow shelving bottom.] - -[116] [ Doubtless the road would pass the harbour in Odyssean times as -it passes the salt works now; indeed, if there is to be a road at all -there is no other level ground which it could take. See map above -referred to.] - -[117] [ The rock at the end of the Northern harbour of Trapani, to -which I suppose the writer of the “Odyssey” to be here referring, still -bears the name Malconsiglio—“the rock of evil counsel.” There is a -legend that it was a ship of Turkish pirates who were intending to -attack Trapani, but the “Madonna di Trapani” crushed them under this -rock just as they were coming into port. My friend Cavaliere -Giannitrapani of Trapani told me that his father used to tell him when -he was a boy that if he would drop exactly three drops of oil on to the -water near the rock, he would see the ship still at the bottom. The -legend is evidently a Christianised version of the Odyssean story, -while the name supplies the additional detail that the disaster -happened in consequence of an evil counsel.] - -[118] [ It would seem then that the ship had got all the way back from -Ithaca in about a quarter of an hour.] - -[119] [ And may we not add “and also to prevent his recognising that he -was only in the place where he had met Nausicaa two days earlier.”] - -[120] [ All this is to excuse the entire absence of Minerva from books -ix.-xii., which I suppose had been written already, before the -authoress had determined on making Minerva so prominent a character.] - -[121] [ We have met with this somewhat lame attempt to cover the -writer’s change of scheme at the end of bk. vi.] - -[122] [ I take the following from The Authoress of the Odyssey, p. 167. -“It is clear from the text that there were two [caves] not one, but -some one has enclosed in brackets the two lines in which the second -cave is mentioned, I presume because he found himself puzzled by having -a second cave sprung upon him when up to this point he had only been -told of one. - -“I venture to think that if he had known the ground he would not have -been puzzled, for there are two caves, distant about 80 or 100 yards -from one another.” The cave in which Ulysses hid his treasure is, as I -have already said, identifiable with singular completeness. The other -cave presents no special features, neither in the poem nor in nature.] - -[123] [ There is no attempt to disguise the fact that Penelope had long -given encouragement to the suitors. The only defence set up is that she -did not really mean to encourage them. Would it not have been wiser to -have tried a little discouragement?] - -[124] [ See map near the end of bk. vi. _Ruccazzù dei corvi_ of course -means “the rock of the ravens.” Both name and ravens still exist.] - -[125] [ See The Authoress of the Odyssey, pp. 140, 141. The real reason -for sending Telemachus to Pylos and Lacedaemon was that the authoress -might get Helen of Troy into her poem. He was sent at the only point in -the story at which he could be sent, so he must have gone then or not -at all.] - -[126] [ The site I assign to Eumaeus’s hut, close to the _Ruccazzù dei -corvi_, is about 2,000 feet above the sea, and commands an extensive -view.] - -[127] [ Sandals such as Eumaeus was making are still worn in the -Abruzzi and elsewhere. An oblong piece of leather forms the sole: holes -are cut at the four corners, and through these holes leathern straps -are passed, which are bound round the foot and cross-gartered up the -calf.] - -[128] [ See note [75] : ] - -[129] [ Telemachus like many another good young man seems to expect -every one to fetch and carry for him.] - -[130] [ “Il.” vi. 288. The store room was fragrant because it was made -of cedar wood. See “Il.” xxiv. 192.] - -[131] [ cf. “Il.” vi. 289 and 293-296. The dress was kept at the bottom -of the chest as one that would only be wanted on the greatest -occasions; but surely the marriage of Hermione and of Megapenthes (bk, -iv. _ad init_.) might have induced Helen to wear it on the preceding -evening, in which case it could hardly have got back. We find no hint -here of Megapenthes’ recent marriage.] - -[132] [ See note [83].] - -[133] [ cf. “Od.” xi. 196, etc.] - -[134] [ The names Syra and Ortygia, on which island a great part of the -Doric Syracuse was originally built, suggest that even in Odyssean -times there was a prehistoric Syracuse, the existence of which was -known to the writer of the poem.] - -[135] [ Literally “where are the turnings of the sun.” Assuming, as we -may safely do, that the Syra and Ortygia of the “Odyssey” refer to -Syracuse, it is the fact that not far to the South of these places the -land turns sharply round, so that mariners following the coast would -find the sun upon the other side of their ship to that on which they’d -had it hitherto. - -Mr. A. S. Griffith has kindly called my attention to Herod iv. 42, -where, speaking of the circumnavigation of Africa by Phoenician -mariners under Necos, he writes: - -“On their return they declared—I for my part do not believe them, but -perhaps others may—that in sailing round Libya [i.e. Africa] they had -the sun upon their right hand. In this way was the extent of Libya -first discovered. - -“I take it that Eumaeus was made to have come from Syracuse because the -writer thought she rather ought to have made something happen at -Syracuse during her account of the voyages of Ulysses. She could not, -however, break his long drift from Charybdis to the island of -Pantellaria; she therefore resolved to make it up to Syracuse in -another way.” - -Modern excavations establish the existence of two and only two -pre-Dorian communities at Syracuse; they were, so Dr. Orsi informed me, -at Plemmirio and Cozzo Pantano. See The Authoress of the Odyssey, pp. -211-213.] - -[136] [ This harbour is again evidently the harbour in which Ulysses -had landed, i.e. the harbour that is now the salt works of S. -Cusumano.] - -[137] [ This never can have been anything but very niggardly pay for -some eight or nine days’ service. I suppose the crew were to consider -the pleasure of having had a trip to Pylos as a set off. There is no -trace of the dinner as having been actually given, either on the -following or any other morning.] - -[138] [ No hawk can tear its prey while it is on the wing.] - -[139] [ The text is here apparently corrupt, and will not make sense as -it stands. I follow Messrs. Butcher & Lang in omitting line 101.] - -[140] [ i.e. to be milked, as in South Italian and Sicilian towns at -the present day.] - -[141] [ The butchering and making ready the carcases took place partly -in the outer yard and partly in the open part of the inner court.] - -[142] [ These words cannot mean that it would be afternoon soon after -they were spoken. Ulysses and Eumaeus reached the town which was “some -way off” (xvii. 25) in time for the suitor’s early meal (xvii. 170 and -176) say at ten or eleven o’ clock. The context of the rest of the book -shows this. Eumaeus and Ulysses, therefore, cannot have started later -than eight or nine, and Eumaeus’s words must be taken as an -exaggeration for the purpose of making Ulysses bestir himself.] - -[143] [ I imagine the fountain to have been somewhere about where the -church of the _Madonna di Trapani_ now stands, and to have been fed -with water from what is now called the Fontana Diffali on Mt. Eryx.] - -[144] [ From this and other passages in the “Odyssey” it appears that -we are in an age anterior to the use of coined money—an age when -cauldrons, tripods, swords, cattle, chattels of all kinds, measures of -corn, wine, or oil, etc. etc., not to say pieces of gold, silver, -bronze, or even iron, wrought more or less, but unstamped, were the -nearest approach to a currency that had as yet been reached.] - -[145] [ Gr. ἐς μέσσον.] - -[146] [ I correct these proofs abroad and am not within reach of -Hesiod, but surely this passage suggests acquaintance with the Works -and Ways, though it by no means compels it.] - -[147] [ It would seem as though Eurynome and Euryclea were the same -person. See note 156] - -[148] [ It is plain, therefore, that Iris was commonly accepted as the -messenger of the gods, though our authoress will never permit her to -fetch or carry for any one.] - -[149] [ i.e. the doorway leading from the inner to the outer court.] - -[150] [See note 156] - -[151] [ These, I imagine, must have been in the open part of the inner -courtyard, where the maids also stood, and threw the light of their -torches into the covered cloister that ran all round it. The smoke -would otherwise have been intolerable.] - -[152] [ Translation very uncertain; vide Liddell and Scott, under -{Greek}] - -[153] [ See photo on opposite page.] - -[154] [ cf. “Il.” ii. 184, and 217, 218. An additional and well-marked -feature being wanted to convince Penelope, the writer has taken the -hunched shoulders of Thersites (who is mentioned immediately after -Eurybates in the “Iliad”) and put them on to Eurybates’ back.] - -[155] [ This is how geese are now fed in Sicily, at any rate in summer, -when the grass is all burnt up. I have never seen them grazing.] - -[156] [ Lower down (line 143) Euryclea says it was herself that had -thrown the cloak over Ulysses—for the plural should not be taken as -implying more than one person. The writer is evidently still -fluctuating between Euryclea and Eurynome as the name for the old -nurse. She probably originally meant to call her Euryclea, but finding -it not immediately easy to make Euryclea scan in xvii. 495, she hastily -called her Eurynome, intending either to alter this name later or to -change the earlier Euryclea’s into Eurynome. She then drifted in to -Eurynome as convenience further directed, still nevertheless hankering -after Euryclea, till at last she found that the path of least -resistance would lie in the direction of making Eurynome and Euryclea -two persons. Therefore in xxiii. 289-292 both Eurynome and “the nurse” -(who can be none other than Euryclea) come on together. I do not say -that this is feminine, but it is not unfeminine.] - -[157] [ See note [156]] - -[158] [ This, I take it, was immediately in front of the main entrance -of the inner courtyard into the body of the house.] - -[159] [ This is the only allusion to Sardinia in either “Iliad” or -“Odyssey.”] - -[160] [ The normal translation of the Greek word would be “holding -back,” “curbing,” “restraining,” but I cannot think that the writer -meant this—she must have been using the word in its other sense of -“having,” “holding,” “keeping,” “maintaining.”] - -[161] [ I have vainly tried to realise the construction of the -fastening here described.] - -[162] [ See plan of Ulysses’ house in the appendix. It is evident that -the open part of the court had no flooring but the natural soil.] - -[163] [ See plan of Ulysses’ house, and note [175].] - -[164] [ i.e. the door that led into the body of the house.] - -[165] [ This was, no doubt, the little table that was set for Ulysses, -“Od.” xx. 259. - -Surely the difficulty of this passage has been overrated. I suppose the -iron part of the axe to have been wedged into the handle, or bound -securely to it—the handle being half buried in the ground. The axe -would be placed edgeways towards the archer, and he would have to shoot -his arrow through the hole into which the handle was fitted when the -axe was in use. Twelve axes were placed in a row all at the same -height, all exactly in front of one another, all edgeways to Ulysses -whose arrow passed through all the holes from the first onward. I -cannot see how the Greek can bear any other interpretation, the words -being, {Greek} - -“He did not miss a single hole from the first onwards.” {Greek} -according to Liddell and Scott being “the hole for the handle of an -axe, etc.,” while {Greek} (“Od.” v. 236) is, according to the same -authorities, the handle itself. The feat is absurdly impossible, but -our authoress sometimes has a soul above impossibilities.] - -[166] [ The reader will note how the spoiling of good food distresses -the writer even in such a supreme moment as this.] - -[167] [ Here we have it again. Waste of substance comes first.] - -[168] [ cf. “Il.” iii. 337 and three other places. It is strange that -the author of the “Iliad” should find a little horse-hair so alarming. -Possibly enough she was merely borrowing a common form line from some -earlier poet—or poetess—for this is a woman’s line rather than a -man’s.] - -[169] [ Or perhaps simply “window.” See plan in the appendix.] - -[170] [ i.e. the pavement on which Ulysses was standing.] - -[171] [ The interpretation of lines 126-143 is most dubious, and at -best we are in a region of melodrama: cf., however, i. 425, etc. from -which it appears that there was a tower in the outer court, and that -Telemachus used to sleep in it. The ὀρσοθύρα I take to be a door, or -trap door, leading on to the roof above Telemachus’s bed room, which we -are told was in a place that could be seen from all round—or it might -be simply a window in Telemachus’s room looking out into the street. -From the top of the tower the outer world was to be told what was going -on, but people could not get in by the ὀρσοθύρα: they would have to -come in by the main entrance, and Melanthius explains that the mouth of -the narrow passage (which was in the lands of Ulysses and his friends) -commanded the only entrance by which help could come, so that there -would be nothing gained by raising an alarm. - As for the ῥῶγες of line 143, no commentator ancient or modern has - been able to say what was intended—but whatever they were, - Melanthius could never carry twelve shields, twelve helmets, and - twelve spears. Moreover, where he could go the others could go - also. If a dozen suitors had followed Melanthius into the house - they could have attacked Ulysses in the rear, in which case, unless - Minerva had intervened promptly, the “Odyssey” would have had a - different ending. But throughout the scene we are in a region of - extravagance rather than of true fiction—it cannot be taken - seriously by any but the very serious, until we come to the episode - of Phemius and Medon, where the writer begins to be at home again.] - -[172] [ I presume it was intended that there should be a hook driven -into the bearing-post.] - -[173] [ What for?] - -[174] [ Gr: {Greek}. This is not {Greek}.] - -[175] [ From lines 333 and 341 of this book, and lines 145 and 146 of -bk. xxi we can locate the approach to the {Greek} with some certainty.] - -[176] [ But in xix. 500-502 Ulysses scolded Euryclea for offering -information on this very point, and declared himself quite able to -settle it for himself.] - -[177] [ There were a hundred and eight Suitors.] - -[178] [ Lord Grimthorpe, whose understanding does not lend itself to -easy imposition, has been good enough to write to me about my -conviction that the “Odyssey” was written by a woman, and to send me -remarks upon the gross absurdity of the incident here recorded. It is -plain that all the authoress cared about was that the women should be -hanged: as for attempting to realise, or to make her readers realise, -how the hanging was done, this was of no consequence. The reader must -take her word for it and ask no questions. Lord Grimthorpe wrote: - -“I had better send you my ideas about Nausicaa’s hanging of the maids -(not ‘maidens,’ of whom Froude wrote so well in his ‘Science of -History’) before I forget it all. Luckily for me Liddell & Scott have -specially translated most of the doubtful words, referring to this very -place. - -“A ship’s cable. I don’t know how big a ship she meant, but it must -have been a very small one indeed if its ‘cable’ could be used to tie -tightly round a woman’s neck, and still more round a dozen of them ‘in -a row,’ besides being strong enough to hold them and pull them all up. - -“A dozen average women would need the weight and strength of more than -a dozen strong heavy men even over the best pulley hung to the roof -over them; and the idea of pulling them up by a rope hung anyhow round -a pillar {Greek} is absurdly impossible; and how a dozen of them could -be hung dangling round one post is a problem which a senior wrangler -would be puzzled to answer... She had better have let Telemachus use -his sword as he had intended till she changed his mind for him.”] - -[179] [ Then they had all been in Ulysses’ service over twenty years; -perhaps the twelve guilty ones had been engaged more recently.] - -[180] [ Translation very doubtful—cf. “It.” xxiv. 598.] - -[181] [ But why could she not at once ask to see the scar, of which -Euryclea had told her, or why could not Ulysses have shown it to her?] - -[182] [ The people of Ithaca seem to have been as fond of carping as -the Phaeacians were in vi. 273, etc.] - -[183] [ See note [156]. Ulysses’s bed room does not appear to have been -upstairs, nor yet quite within the house. Is it possible that it was -“the domed room” round the outside of which the erring maids were, for -aught we have heard to the contrary, still hanging?] - -[184] [ Ulysses bedroom in the mind of the writer is here too -apparently down stairs.] - -[185] [ Penelope having been now sufficiently whitewashed, disappears -from the poem.] - -[186] [ So practised a washerwoman as our authoress doubtless knew that -by this time the web must have become such a wreck that it would have -gone to pieces in the wash.] - -A lady points out to me, just as these sheets are leaving my hands, -that no really good needlewoman—no one, indeed, whose work or character -was worth consideration—could have endured, no matter for what reason, -the unpicking of her day’s work, day after day for between three and -four years.] - -[187] [ We must suppose Dolius not yet to know that his son Melanthius -had been tortured, mutilated, and left to die by Ulysses’ orders on the -preceding day, and that his daughter Melantho had been hanged. Dolius -was probably exceptionally simple-minded, and his name was ironical. So -on Mt. Eryx I was shown a man who was always called Sonza Malizia or -“Guileless”—he being held exceptionally cunning.] - - - - - - -*** END OF THE PROJECT GUTENBERG EBOOK THE ODYSSEY *** - - - - -Updated editions will replace the previous one—the old editions will -be renamed. - -Creating the works from print editions not protected by U.S. copyright -law means that no one owns a United States copyright in these works, -so the Foundation (and you!) can copy and distribute it in the United -States without permission and without paying copyright -royalties. Special rules, set forth in the General Terms of Use part -of this license, apply to copying and distributing Project -Gutenberg™ electronic works to protect the PROJECT GUTENBERG™ -concept and trademark. Project Gutenberg is a registered trademark, -and may not be used if you charge for an eBook, except by following -the terms of the trademark license, including paying royalties for use -of the Project Gutenberg trademark. If you do not charge anything for -copies of this eBook, complying with the trademark license is very -easy. You may use this eBook for nearly any purpose such as creation -of derivative works, reports, performances and research. Project -Gutenberg eBooks may be modified and printed and given away—you may -do practically ANYTHING in the United States with eBooks not protected -by U.S. copyright law. Redistribution is subject to the trademark -license, especially commercial redistribution. - - -START: FULL LICENSE - -THE FULL PROJECT GUTENBERG LICENSE - -PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK - -To protect the Project Gutenberg™ mission of promoting the free -distribution of electronic works, by using or distributing this work -(or any other work associated in any way with the phrase “Project -Gutenberg”), you agree to comply with all the terms of the Full -Project Gutenberg™ License available with this file or online at -www.gutenberg.org/license. - -Section 1. General Terms of Use and Redistributing Project Gutenberg™ -electronic works - -1.A. By reading or using any part of this Project Gutenberg™ -electronic work, you indicate that you have read, understand, agree to -and accept all the terms of this license and intellectual property -(trademark/copyright) agreement. If you do not agree to abide by all -the terms of this agreement, you must cease using and return or -destroy all copies of Project Gutenberg™ electronic works in your -possession. If you paid a fee for obtaining a copy of or access to a -Project Gutenberg™ electronic work and you do not agree to be bound -by the terms of this agreement, you may obtain a refund from the person -or entity to whom you paid the fee as set forth in paragraph 1.E.8. - -1.B. “Project Gutenberg” is a registered trademark. It may only be -used on or associated in any way with an electronic work by people who -agree to be bound by the terms of this agreement. There are a few -things that you can do with most Project Gutenberg™ electronic works -even without complying with the full terms of this agreement. See -paragraph 1.C below. There are a lot of things you can do with Project -Gutenberg™ electronic works if you follow the terms of this -agreement and help preserve free future access to Project Gutenberg™ -electronic works. See paragraph 1.E below. - -1.C. The Project Gutenberg Literary Archive Foundation (“the -Foundation” or PGLAF), owns a compilation copyright in the collection -of Project Gutenberg™ electronic works. Nearly all the individual -works in the collection are in the public domain in the United -States. If an individual work is unprotected by copyright law in the -United States and you are located in the United States, we do not -claim a right to prevent you from copying, distributing, performing, -displaying or creating derivative works based on the work as long as -all references to Project Gutenberg are removed. Of course, we hope -that you will support the Project Gutenberg™ mission of promoting -free access to electronic works by freely sharing Project Gutenberg™ -works in compliance with the terms of this agreement for keeping the -Project Gutenberg™ name associated with the work. You can easily -comply with the terms of this agreement by keeping this work in the -same format with its attached full Project Gutenberg™ License when -you share it without charge with others. - -1.D. The copyright laws of the place where you are located also govern -what you can do with this work. Copyright laws in most countries are -in a constant state of change. If you are outside the United States, -check the laws of your country in addition to the terms of this -agreement before downloading, copying, displaying, performing, -distributing or creating derivative works based on this work or any -other Project Gutenberg™ work. The Foundation makes no -representations concerning the copyright status of any work in any -country other than the United States. - -1.E. Unless you have removed all references to Project Gutenberg: - -1.E.1. The following sentence, with active links to, or other -immediate access to, the full Project Gutenberg™ License must appear -prominently whenever any copy of a Project Gutenberg™ work (any work -on which the phrase “Project Gutenberg” appears, or with which the -phrase “Project Gutenberg” is associated) is accessed, displayed, -performed, viewed, copied or distributed: - - This eBook is for the use of anyone anywhere in the United States and most - other parts of the world at no cost and with almost no restrictions - whatsoever. You may copy it, give it away or re-use it under the terms - of the Project Gutenberg License included with this eBook or online - at www.gutenberg.org. If you - are not located in the United States, you will have to check the laws - of the country where you are located before using this eBook. - -1.E.2. If an individual Project Gutenberg™ electronic work is -derived from texts not protected by U.S. copyright law (does not -contain a notice indicating that it is posted with permission of the -copyright holder), the work can be copied and distributed to anyone in -the United States without paying any fees or charges. If you are -redistributing or providing access to a work with the phrase “Project -Gutenberg” associated with or appearing on the work, you must comply -either with the requirements of paragraphs 1.E.1 through 1.E.7 or -obtain permission for the use of the work and the Project Gutenberg™ -trademark as set forth in paragraphs 1.E.8 or 1.E.9. - -1.E.3. If an individual Project Gutenberg™ electronic work is posted -with the permission of the copyright holder, your use and distribution -must comply with both paragraphs 1.E.1 through 1.E.7 and any -additional terms imposed by the copyright holder. Additional terms -will be linked to the Project Gutenberg™ License for all works -posted with the permission of the copyright holder found at the -beginning of this work. - -1.E.4. Do not unlink or detach or remove the full Project Gutenberg™ -License terms from this work, or any files containing a part of this -work or any other work associated with Project Gutenberg™. - -1.E.5. Do not copy, display, perform, distribute or redistribute this -electronic work, or any part of this electronic work, without -prominently displaying the sentence set forth in paragraph 1.E.1 with -active links or immediate access to the full terms of the Project -Gutenberg™ License. - -1.E.6. You may convert to and distribute this work in any binary, -compressed, marked up, nonproprietary or proprietary form, including -any word processing or hypertext form. However, if you provide access -to or distribute copies of a Project Gutenberg™ work in a format -other than “Plain Vanilla ASCII” or other format used in the official -version posted on the official Project Gutenberg™ website -(www.gutenberg.org), you must, at no additional cost, fee or expense -to the user, provide a copy, a means of exporting a copy, or a means -of obtaining a copy upon request, of the work in its original “Plain -Vanilla ASCII” or other form. Any alternate format must include the -full Project Gutenberg™ License as specified in paragraph 1.E.1. - -1.E.7. Do not charge a fee for access to, viewing, displaying, -performing, copying or distributing any Project Gutenberg™ works -unless you comply with paragraph 1.E.8 or 1.E.9. - -1.E.8. You may charge a reasonable fee for copies of or providing -access to or distributing Project Gutenberg™ electronic works -provided that: - - • You pay a royalty fee of 20% of the gross profits you derive from - the use of Project Gutenberg™ works calculated using the method - you already use to calculate your applicable taxes. The fee is owed - to the owner of the Project Gutenberg™ trademark, but he has - agreed to donate royalties under this paragraph to the Project - Gutenberg Literary Archive Foundation. Royalty payments must be paid - within 60 days following each date on which you prepare (or are - legally required to prepare) your periodic tax returns. Royalty - payments should be clearly marked as such and sent to the Project - Gutenberg Literary Archive Foundation at the address specified in - Section 4, “Information about donations to the Project Gutenberg - Literary Archive Foundation.” - - • You provide a full refund of any money paid by a user who notifies - you in writing (or by e-mail) within 30 days of receipt that s/he - does not agree to the terms of the full Project Gutenberg™ - License. You must require such a user to return or destroy all - copies of the works possessed in a physical medium and discontinue - all use of and all access to other copies of Project Gutenberg™ - works. - - • You provide, in accordance with paragraph 1.F.3, a full refund of - any money paid for a work or a replacement copy, if a defect in the - electronic work is discovered and reported to you within 90 days of - receipt of the work. - - • You comply with all other terms of this agreement for free - distribution of Project Gutenberg™ works. - - -1.E.9. If you wish to charge a fee or distribute a Project -Gutenberg™ electronic work or group of works on different terms than -are set forth in this agreement, you must obtain permission in writing -from the Project Gutenberg Literary Archive Foundation, the manager of -the Project Gutenberg™ trademark. Contact the Foundation as set -forth in Section 3 below. - -1.F. - -1.F.1. Project Gutenberg volunteers and employees expend considerable -effort to identify, do copyright research on, transcribe and proofread -works not protected by U.S. copyright law in creating the Project -Gutenberg™ collection. Despite these efforts, Project Gutenberg™ -electronic works, and the medium on which they may be stored, may -contain “Defects,” such as, but not limited to, incomplete, inaccurate -or corrupt data, transcription errors, a copyright or other -intellectual property infringement, a defective or damaged disk or -other medium, a computer virus, or computer codes that damage or -cannot be read by your equipment. - -1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the “Right -of Replacement or Refund” described in paragraph 1.F.3, the Project -Gutenberg Literary Archive Foundation, the owner of the Project -Gutenberg™ trademark, and any other party distributing a Project -Gutenberg™ electronic work under this agreement, disclaim all -liability to you for damages, costs and expenses, including legal -fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT -LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE -PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE THAT THE FOUNDATION, THE -TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE -LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR -INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH -DAMAGE. - -1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a -defect in this electronic work within 90 days of receiving it, you can -receive a refund of the money (if any) you paid for it by sending a -written explanation to the person you received the work from. If you -received the work on a physical medium, you must return the medium -with your written explanation. The person or entity that provided you -with the defective work may elect to provide a replacement copy in -lieu of a refund. If you received the work electronically, the person -or entity providing it to you may choose to give you a second -opportunity to receive the work electronically in lieu of a refund. If -the second copy is also defective, you may demand a refund in writing -without further opportunities to fix the problem. - -1.F.4. Except for the limited right of replacement or refund set forth -in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO -OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT -LIMITED TO WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PURPOSE. - -1.F.5. Some states do not allow disclaimers of certain implied -warranties or the exclusion or limitation of certain types of -damages. If any disclaimer or limitation set forth in this agreement -violates the law of the state applicable to this agreement, the -agreement shall be interpreted to make the maximum disclaimer or -limitation permitted by the applicable state law. The invalidity or -unenforceability of any provision of this agreement shall not void the -remaining provisions. - -1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the -trademark owner, any agent or employee of the Foundation, anyone -providing copies of Project Gutenberg™ electronic works in -accordance with this agreement, and any volunteers associated with the -production, promotion and distribution of Project Gutenberg™ -electronic works, harmless from all liability, costs and expenses, -including legal fees, that arise directly or indirectly from any of -the following which you do or cause to occur: (a) distribution of this -or any Project Gutenberg™ work, (b) alteration, modification, or -additions or deletions to any Project Gutenberg™ work, and (c) any -Defect you cause. - -Section 2. Information about the Mission of Project Gutenberg™ - -Project Gutenberg™ is synonymous with the free distribution of -electronic works in formats readable by the widest variety of -computers including obsolete, old, middle-aged and new computers. It -exists because of the efforts of hundreds of volunteers and donations -from people in all walks of life. - -Volunteers and financial support to provide volunteers with the -assistance they need are critical to reaching Project Gutenberg™’s -goals and ensuring that the Project Gutenberg™ collection will -remain freely available for generations to come. In 2001, the Project -Gutenberg Literary Archive Foundation was created to provide a secure -and permanent future for Project Gutenberg™ and future -generations. To learn more about the Project Gutenberg Literary -Archive Foundation and how your efforts and donations can help, see -Sections 3 and 4 and the Foundation information page at www.gutenberg.org. - -Section 3. Information about the Project Gutenberg Literary Archive Foundation - -The Project Gutenberg Literary Archive Foundation is a non-profit -501(c)(3) educational corporation organized under the laws of the -state of Mississippi and granted tax exempt status by the Internal -Revenue Service. The Foundation’s EIN or federal tax identification -number is 64-6221541. Contributions to the Project Gutenberg Literary -Archive Foundation are tax deductible to the full extent permitted by -U.S. federal laws and your state’s laws. - -The Foundation’s business office is located at 809 North 1500 West, -Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up -to date contact information can be found at the Foundation’s website -and official page at www.gutenberg.org/contact - -Section 4. Information about Donations to the Project Gutenberg -Literary Archive Foundation - -Project Gutenberg™ depends upon and cannot survive without widespread -public support and donations to carry out its mission of -increasing the number of public domain and licensed works that can be -freely distributed in machine-readable form accessible by the widest -array of equipment including outdated equipment. Many small donations -($1 to $5,000) are particularly important to maintaining tax exempt -status with the IRS. - -The Foundation is committed to complying with the laws regulating -charities and charitable donations in all 50 states of the United -States. Compliance requirements are not uniform and it takes a -considerable effort, much paperwork and many fees to meet and keep up -with these requirements. We do not solicit donations in locations -where we have not received written confirmation of compliance. To SEND -DONATIONS or determine the status of compliance for any particular state -visit www.gutenberg.org/donate. - -While we cannot and do not solicit contributions from states where we -have not met the solicitation requirements, we know of no prohibition -against accepting unsolicited donations from donors in such states who -approach us with offers to donate. - -International donations are gratefully accepted, but we cannot make -any statements concerning tax treatment of donations received from -outside the United States. U.S. laws alone swamp our small staff. - -Please check the Project Gutenberg web pages for current donation -methods and addresses. Donations are accepted in a number of other -ways including checks, online payments and credit card donations. To -donate, please visit: www.gutenberg.org/donate. - -Section 5. General Information About Project Gutenberg™ electronic works - -Professor Michael S. Hart was the originator of the Project -Gutenberg™ concept of a library of electronic works that could be -freely shared with anyone. For forty years, he produced and -distributed Project Gutenberg™ eBooks with only a loose network of -volunteer support. - -Project Gutenberg™ eBooks are often created from several printed -editions, all of which are confirmed as not protected by copyright in -the U.S. unless a copyright notice is included. Thus, we do not -necessarily keep eBooks in compliance with any particular paper -edition. - -Most people start at our website which has the main PG search -facility: www.gutenberg.org. - -This website includes information about Project Gutenberg™, -including how to make donations to the Project Gutenberg Literary -Archive Foundation, how to help produce our new eBooks, and how to -subscribe to our email newsletter to hear about new eBooks. - - diff --git a/symbolicai-main/symbolicai-main/tests/engines/drawing/test_drawing_engine.py b/symbolicai-main/symbolicai-main/tests/engines/drawing/test_drawing_engine.py deleted file mode 100644 index 0e42705f5159cdb799765547aed69b39ab89a4c2..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/engines/drawing/test_drawing_engine.py +++ /dev/null @@ -1,84 +0,0 @@ -import os -from pathlib import Path - -import pytest - -from symai import Symbol -from symai.backend.settings import SYMAI_CONFIG -from symai.extended import Interface - -DRAWING_ENGINE = SYMAI_CONFIG.get("DRAWING_ENGINE_MODEL") - -OAI_MODELS = ["dall-e-2", "dall-e-3", "gpt-image-1"] -BFL_MODELS = ["flux-dev", "flux-pro", "flux-pro-1.1", "flux-pro-1.1-ultra"] - - -@pytest.mark.skipif(not DRAWING_ENGINE.startswith("dall-e-") and not DRAWING_ENGINE.startswith("gpt-image-"), reason="Not an OpenAI model") -@pytest.mark.parametrize("model", OAI_MODELS) -def test_gpt_image_create(model): - gpt_image = Interface('gpt_image') - paths = gpt_image('a fluffy cat with a cowboy hat', model=model, size=1024, response_format='url') - assert os.path.exists(paths[0]) and os.path.getsize(paths[0]) > 0 - - -@pytest.mark.skipif(not DRAWING_ENGINE.startswith("dall-e-") and not DRAWING_ENGINE.startswith("gpt-image-"), reason="Not an OpenAI model") -@pytest.mark.parametrize("model", ['dall-e-2']) -def test_gpt_image_variation(model): - img_path = Path(__file__).parent.parent.parent.parent / 'assets' / 'images' / 'cat.png' - gpt_image = Interface('gpt_image') - paths = gpt_image( - operation='variation', - model=model, - image_path=img_path, - n=1, - size=1024, - response_format='url', - ) - assert os.path.exists(paths[0]) and os.path.getsize(paths[0]) > 0 - - -@pytest.mark.skipif(not DRAWING_ENGINE.startswith("dall-e-") and not DRAWING_ENGINE.startswith("gpt-image-"), reason="Not an OpenAI model") -@pytest.mark.skipif(DRAWING_ENGINE.startswith("dall-e-"), reason="For whatever reason, this test doesn't work for dall-e-2 even though I followed the documentation. Not sure what's wrong. Maybe it's a bug in the OpenAI API (testing version: openai==1.76.0") -@pytest.mark.parametrize("model,quality", [('gpt-image-1', 'medium')]) -def test_gpt_image_edit(model, quality): - img_path = Path(__file__).parent.parent.parent.parent / 'assets' / 'images' / 'cat.png' - gpt_image = Interface('gpt_image') - - prompt = ( - "Convert the cat in this image into a character from The Elder Scrolls IV: Oblivion, " - "complete with medieval armor, a nocturnal-fantasy style helmet, zoomed out, and ancient scrolls in the background." - ) - - paths = gpt_image( - prompt=prompt, - operation='edit', - model=model, - image_path=img_path, - n=1, - size=1024, - quality=quality, - ) - - assert os.path.exists(paths[0]) and os.path.getsize(paths[0]) > 0 - - -@pytest.mark.skipif(not DRAWING_ENGINE.startswith("flux"), reason="Not a Black Forest Labs model") -@pytest.mark.parametrize("model", BFL_MODELS) -def test_flux_image_create(model): - flux = Interface('flux') - paths = flux( - "a fluffy cat with a cowboy hat", - operation='create', - model=model, - width=1024, - height=768, - steps=50, - guidance=7.5, - seed=42, - safety_tolerance=2 - ) - assert os.path.exists(paths[0]) and os.path.getsize(paths[0]) > 0 - - -if __name__ == '__main__': - pytest.main() diff --git a/symbolicai-main/symbolicai-main/tests/engines/neurosymbolic/test_nesy_engine.py b/symbolicai-main/symbolicai-main/tests/engines/neurosymbolic/test_nesy_engine.py deleted file mode 100644 index bacaa52e3436301bb34317e1fa97e87ec1230412..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/engines/neurosymbolic/test_nesy_engine.py +++ /dev/null @@ -1,257 +0,0 @@ -from pathlib import Path - -import pytest -from anthropic import Stream -from anthropic.types import ToolUseBlock -from anthropic.types.message import Message -from google.genai import types # Import for Gemini types -from numpy import add -from openai.types.chat.chat_completion import ChatCompletion - -from symai import Expression, Symbol -from symai.backend.settings import SYMAI_CONFIG -from symai.components import Function -from symai.core_ext import bind - -NEUROSYMBOLIC = SYMAI_CONFIG.get('NEUROSYMBOLIC_ENGINE_MODEL') -CLAUDE_THINKING = {"budget_tokens": 1024} -GEMINI_THINKING = {"thinking_budget": 1024} -CLAUDE_MAX_TOKENS = 4092 - -@bind(engine='neurosymbolic', property='compute_required_tokens')(lambda: 0) -def _compute_required_tokens(): pass - -@pytest.mark.mandatory -def test_init(): - x = Symbol('This is a test!') - - if all(id not in NEUROSYMBOLIC for id in ['3-7', '4-0']): - x.query('What is this?') - else: - x.query('What is this?', max_tokens=CLAUDE_MAX_TOKENS, thinking=CLAUDE_THINKING, raw_output=True) - - # if no errors are raised, then the test is successful - assert True - -@pytest.mark.mandatory -@pytest.mark.skipif(NEUROSYMBOLIC.startswith('llama'), reason='feature not yet implemented') -@pytest.mark.skipif(NEUROSYMBOLIC.startswith('huggingface'), reason='feature not yet implemented') -@pytest.mark.skipif(NEUROSYMBOLIC.startswith('o3-mini'), reason='feature not supported by the model') -def test_vision(): - file = Path(__file__).parent.parent.parent.parent / 'assets' / 'images' / 'cat.jpg' - x = Symbol(f'<>') - if all(id not in NEUROSYMBOLIC for id in ['3-7', '4-0']): - res = x.query('What is in the image?') - else: - res = x.query('What is in the image?', max_tokens=CLAUDE_MAX_TOKENS, thinking=CLAUDE_THINKING) - - # it makes sense here to explicitly check if there is a cat; we are testing the vision component - assert 'cat' in res.value - - file = 'https://raw.githubusercontent.com/ExtensityAI/symbolicai/main/assets/images/cat.jpg' - x = Symbol(f'<>') - - if all(id not in NEUROSYMBOLIC for id in ['3-7', '4-0']): - res = x.query('What is in the image?') - else: - res = x.query('What is in the image?', max_tokens=CLAUDE_MAX_TOKENS, thinking=CLAUDE_THINKING) - - # same check but for url - assert 'cat' in res.value - -@pytest.mark.mandatory -@pytest.mark.skipif(NEUROSYMBOLIC.startswith('llama'), reason='llamacpp tokens computation is not yet implemented') -@pytest.mark.skipif(NEUROSYMBOLIC.startswith('huggingface'), reason='huggingface tokens computation is not yet implemented') -def test_tokenizer(): - if NEUROSYMBOLIC.startswith('gemini'): - messages = [ - {"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."}, - {"role": "user", "content": "New synergies will help drive top-line growth."}, - {"role": "model", "content": "Things working well together will increase revenue."}, - {"role": "user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."}, - {"role": "model", "content": "Let's talk later when we're less busy about how to do better."}, - {"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."} - ] - elif NEUROSYMBOLIC.startswith('claude'): - messages = [ - {"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."}, - {"role": "user", "content": "New synergies will help drive top-line growth."}, - {"role": "assistant", "content": "Things working well together will increase revenue."}, - {"role": "user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."}, - {"role": "assistant", "content": "Let's talk later when we're less busy about how to do better."}, - {"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."} - ] - else: - admin_role = 'system' if NEUROSYMBOLIC.startswith('gpt') else 'developer' - messages = [ - {"role": admin_role, "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."}, - {"role": admin_role, "name": "example_user", "content": "New synergies will help drive top-line growth."}, - {"role": admin_role, "name": "example_assistant", "content": "Things working well together will increase revenue."}, - {"role": admin_role, "name": "example_user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."}, - {"role": admin_role, "name": "example_assistant", "content": "Let's talk later when we're less busy about how to do better."}, - {"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."} - ] - - response = Expression.prompt(messages, raw_output=True) - - if NEUROSYMBOLIC.startswith('gemini'): - api_tokens = response.usage_metadata.prompt_token_count - elif NEUROSYMBOLIC.startswith('claude'): - api_tokens = response[0].message.usage.input_tokens - else: - api_tokens = response.usage.prompt_tokens - - tik_tokens = _compute_required_tokens(messages) - - assert api_tokens == tik_tokens - -@pytest.mark.mandatory -@pytest.mark.skipif(NEUROSYMBOLIC.startswith('llama'), reason='feature not yet implemented') -@pytest.mark.skipif(NEUROSYMBOLIC.startswith('huggingface'), reason='feature not yet implemented') -@pytest.mark.skipif(NEUROSYMBOLIC.startswith('o1'), reason='feature not supported by the model') -def test_tool_usage(): - if NEUROSYMBOLIC.startswith('o3') or NEUROSYMBOLIC.startswith('o4') or NEUROSYMBOLIC.startswith('gpt'): - tools = [{ - "type": "function", - "function": { - "name": "get_weather", - "description": "Get current temperature for a given location.", - "parameters": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "City and country e.g. Bogotá, Colombia" - } - }, - "required": ["location"], - } - } - }] - fn = Function("Analyze the input request and select the most appropriate function to call from the provided options.", tools=tools) - res, metadata = fn("what's the temperature in Bogotá, Colombia", raw_output=True, return_metadata=True) - assert 'function_call' in metadata - assert metadata['function_call']['name'] == 'get_weather' - assert 'location' in metadata['function_call']['arguments'] - assert 'bogotá, colombia' in metadata['function_call']['arguments']['location'].lower() - elif NEUROSYMBOLIC.startswith('claude'): - tools = [ - { - "name": "get_stock_price", - "description": "Get the current stock price for a given ticker symbol.", - "input_schema": { - "type": "object", - "properties": { - "ticker": { - "type": "string", - "description": "The stock ticker symbol, e.g. AAPL for Apple Inc." - } - }, - "required": ["ticker"] - } - } - ] - fn = Function("Analyze the input request and select the most appropriate function to call from the provided options.", tools=tools) - res, metadata = fn("What's the S&P 500 at today", raw_output=True, max_tokens=CLAUDE_MAX_TOKENS, thinking=CLAUDE_THINKING, return_metadata=True) - assert 'function_call' in metadata - assert metadata['function_call']['name'] == 'get_stock_price' - assert 'ticker' in metadata['function_call']['arguments'] - assert 'spy' in metadata['function_call']['arguments']['ticker'].lower() - elif NEUROSYMBOLIC.startswith('gemini'): - # Test case 1: Callable Python function - def get_capital(country: str | None = None) -> str: - """Gets the capital city of a given country.""" - return "Paris" - - tools = [get_capital] - fn = Function("Analyze the input request and select the most appropriate function to call from the provided options.", tools=tools) - res, metadata = fn("What's the capital of France?", raw_output=True, thinking=GEMINI_THINKING, return_metadata=True) - - assert 'function_call' in metadata, 'Could fail if the function call is not recognized by the model; retry.' - assert metadata['function_call']['name'] == 'get_capital' - assert 'country' in metadata['function_call']['arguments'] - assert 'france' in metadata['function_call']['arguments']['country'].lower() - - # Test case 2: google.genai.types.Tool format - fn_decl = types.FunctionDeclaration( - name='get_current_weather', - description='Get the current weather in a given location', - parameters=types.Schema( - type='OBJECT', - properties={ - 'location': types.Schema( - type='STRING', - description='The city and state, e.g. San Francisco, CA', - ), - }, - required=['location'], - ), - ) - - tools = [fn_decl] - fn = Function("Analyze the input request and select the most appropriate function to call from the provided options.", tools=tools) - res, metadata = fn("What is the weather like in Boston?", raw_output=True, thinking=GEMINI_THINKING, return_metadata=True) - - assert 'function_call' in metadata - assert metadata['function_call']['name'] == 'get_current_weather' - assert 'location' in metadata['function_call']['arguments'] - assert 'boston' in metadata['function_call']['arguments']['location'].lower() - -@pytest.mark.mandatory -def test_raw_output(): - if NEUROSYMBOLIC.startswith('claude'): - if all(id not in NEUROSYMBOLIC for id in ['3-7', '4-0']): - S = Expression.prompt('What is the capital of France?', raw_output=True) - else: - S = Expression.prompt('What is the capital of France?', raw_output=True, max_tokens=CLAUDE_MAX_TOKENS, thinking=CLAUDE_THINKING) - assert isinstance(S.value, Message) or isinstance(S.value, Stream) - elif NEUROSYMBOLIC.startswith('gpt') or NEUROSYMBOLIC.startswith('o1') or NEUROSYMBOLIC.startswith('o3'): - S = Expression.prompt('What is the capital of France?', raw_output=True) - assert isinstance(S.value, ChatCompletion) - elif NEUROSYMBOLIC.startswith('gemini'): - S = Expression.prompt('What is the capital of France?', raw_output=True) - assert isinstance(S.value, types.GenerateContentResponse) - -@pytest.mark.mandatory -def test_preview(): - preview_function = Function( - "Return a JSON markdown string representation of the text, no matter what text is provided.", - static_context="This is a static context.", - dynamic_context="This is a dynamic context." - ) - preview = preview_function("Hello, World!", preview=True) - # assert that the output property `processed_input` is as expected - assert preview.prop.processed_input == "Hello, World!" - -@pytest.mark.skipif(NEUROSYMBOLIC.startswith('claude'), reason='Claude tokens computation is not yet implemented') -@pytest.mark.skipif(NEUROSYMBOLIC.startswith('gemini'), reason='Claude tokens computation is not yet implemented') -def test_token_truncator(): - file_path = (Path(__file__).parent.parent.parent / 'data/pg1727.txt').as_posix() - content = Symbol(file_path).open() - admin_role = 'system' if NEUROSYMBOLIC.startswith('gpt') else 'developer' - - # Case 1; user exceeds - _ = Expression.prompt([ - {'role': 'user', 'content': content.value}, - {'role': 'user', 'content': "What's the most tragic event in the novel?"} - ]) - - # Case 2; system exceeds - _ = Expression.prompt([ - {'role': admin_role, 'content': content.value}, - {'role': 'user', 'content': "What's the most tragic event in the novel?"} - ]) - - # Case 3; both exceed - _ = Expression.prompt([ - {'role': admin_role, 'content': content.value}, - {'role': 'user', 'content': content.value + "What's the most tragic event in the novel?"} - ]) - - # Try from Symbol too - _ = content.query("What's the most tragic event in the novel?") - - assert True - -if __name__ == '__main__': - pytest.main() diff --git a/symbolicai-main/symbolicai-main/tests/engines/search/openai.py b/symbolicai-main/symbolicai-main/tests/engines/search/openai.py deleted file mode 100644 index 8fd52002690604d3a9a94cef0ff46644d729782c..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/engines/search/openai.py +++ /dev/null @@ -1,119 +0,0 @@ -import json -import os -import re - -import pytest -from pydantic import BaseModel - -from symai import Interface -from symai.backend.engines.search.engine_openai import SearchResult -from symai.backend.mixin import OPENAI_CHAT_MODELS, OPENAI_REASONING_MODELS -from symai.backend.settings import SYMAI_CONFIG - -API_KEY = bool(SYMAI_CONFIG.get('SEARCH_ENGINE_API_KEY', None)) -MODEL = SYMAI_CONFIG.get('SEARCH_ENGINE_MODEL', '') in OPENAI_CHAT_MODELS + OPENAI_REASONING_MODELS - -pytestmark = [ - pytest.mark.search_engine, - pytest.mark.skipif(not API_KEY, reason="SEARCH_ENGINE_API_KEY not configured or missing."), - pytest.mark.skipif(not MODEL, reason="SEARCH_ENGINE_MODEL is not OpenAI chat model.") -] - -try: - search_interface = Interface('openai_search') -except Exception as e: - search_interface = None - pytestmark.append(pytest.mark.skipif(True, reason=f"OpenAI search interface initialization failed: {e}")) - -@pytest.fixture(scope="module") -def openai_search_interface(): - if search_interface is None: - pytest.skip("OpenAI search interface not available.") - return search_interface - -def test_openai_search_basic_query(openai_search_interface): - """Test a basic query to OpenAI search.""" - query = "Who is Nicusor Dan?" - res = openai_search_interface(query) - - assert isinstance(res, SearchResult), "Response should be a SearchResult instance." - assert res.value is not None, "Response value should not be None." - assert isinstance(res.value, str), "Response value should be a string." - assert len(res.value) > 0, "Response value should not be empty." - - citations = res.get_citations() - assert isinstance(citations, list), "get_citations should return a list" - if citations: - citation_ids = set(citation.id for citation in citations) - for cid in citation_ids: - assert cid in res.value, f"Citation {cid} should appear in text" - -def test_openai_search_with_user_location(openai_search_interface): - """Test OpenAI search with user location customization.""" - query = "What are popular tourist attractions nearby?" - location_config = { - "user_location": { - "type": "approximate", - "country": "US", - "city": "New York", - "region": "New York" - } - } - - res = openai_search_interface(query, **location_config) - - assert isinstance(res, SearchResult) - assert res.value is not None - assert isinstance(res.value, str) - assert len(res.value) > 0 - - location_terms = ["New York", "NYC", "Manhattan", "Brooklyn"] - has_location_relevance = any(term.lower() in res.value.lower() for term in location_terms) - if not has_location_relevance: - pytest.skip("Response did not contain location-relevant information - API specifics may vary") - -def test_openai_search_with_timezone(openai_search_interface): - """Test OpenAI search with timezone in user location.""" - query = "What local events are happening today?" - timezone_config = { - "user_location": { - "type": "approximate", - "country": "JP", - "city": "Tokyo", - "region": "Tokyo", - "timezone": "Asia/Tokyo" - } - } - - res = openai_search_interface(query, **timezone_config) - - assert isinstance(res, SearchResult) - assert res.value is not None - assert isinstance(res.value, str) - assert len(res.value) > 0 - - timezone_terms = ["Japan", "Tokyo", "JST"] - has_timezone_relevance = any(term.lower() in res.value.lower() for term in timezone_terms) - if not has_timezone_relevance: - pytest.skip("Response did not contain location-relevant information - API specifics may vary") - -def test_openai_search_context_size(openai_search_interface): - """Test OpenAI search with different context size settings.""" - query = "Explain quantum computing developments" - - try: - low_config = {"search_context_size": "low"} - low_res = openai_search_interface(query, **low_config) - - assert isinstance(low_res, SearchResult) - assert low_res.value is not None - assert len(low_res.value) > 0 - - high_config = {"search_context_size": "high"} - high_res = openai_search_interface(query, **high_config) - - assert isinstance(high_res, SearchResult) - assert high_res.value is not None - assert len(high_res.value) > 0 - except Exception as e: - pytest.skip(f"Search context size test failed with error: {str(e)}") diff --git a/symbolicai-main/symbolicai-main/tests/engines/search/perplexity.py b/symbolicai-main/symbolicai-main/tests/engines/search/perplexity.py deleted file mode 100644 index 9ead5609aa886b62fe8c2436d8692b910278feb5..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/engines/search/perplexity.py +++ /dev/null @@ -1,234 +0,0 @@ -import json -import os -import re - -import pytest -from pydantic import BaseModel - -from symai import Interface -from symai.backend.engines.search.engine_perplexity import SearchResult -from symai.backend.settings import SYMAI_CONFIG - -API_KEY = bool(SYMAI_CONFIG.get('SEARCH_ENGINE_API_KEY', None)) -MODEL = SYMAI_CONFIG.get('SEARCH_ENGINE_MODEL', '').startswith('sonar') - -pytestmark = [ - pytest.mark.searchengine, - pytest.mark.skipif(not API_KEY, reason="SEARCH_ENGINE_API_KEY not configured or missing."), - pytest.mark.skipif(not MODEL, reason="SEARCH_ENGINE_MODEL is not 'sonar' or sonar-compatible.") -] - -try: - search_interface = Interface('perplexity') -except Exception as e: - search_interface = None - pytestmark.append(pytest.mark.skipif(True, reason=f"Perplexity interface initialization failed: {e}")) - - -@pytest.fixture(scope="module") -def perplexity_interface(): - if search_interface is None: - pytest.skip("Perplexity interface not available.") - return search_interface - - -def test_perplexity_basic_query(perplexity_interface): - """Test a basic query to Perplexity.""" - query = "What is the capital of France?" - res = perplexity_interface(query) - assert isinstance(res, SearchResult), "Response should be a SearchResult instance." - assert res._value is not None, "Response value should not be None." - assert isinstance(res._value, str), "Response value should be a string." - assert len(res._value) > 0, "Response value should not be empty." - assert "Paris" in res._value, "Response for capital of France should contain 'Paris'." - - -def test_perplexity_custom_system_message(perplexity_interface): - """Test Perplexity with a custom system message.""" - query = "Explain black holes." - system_message = "Explain like I'm five years old." - res = perplexity_interface(query, system_message=system_message) - assert isinstance(res, SearchResult) - assert res._value is not None and len(res._value) > 0 - - -def test_perplexity_max_tokens(perplexity_interface): - """Test Perplexity with max_tokens parameter.""" - query = "Tell me a very short story about a robot." - max_tokens_val = 30 - res = perplexity_interface(query, max_tokens=max_tokens_val) - assert isinstance(res, SearchResult) - assert res._value is not None and len(res._value) > 0 - # A rough check for length; tokenization varies. - # This is a heuristic, not a strict guarantee. - assert len(res._value.split()) < max_tokens_val * 3, f"Response seems too long for max_tokens={max_tokens_val}" - - -def test_perplexity_temperature(perplexity_interface): - """Test Perplexity with different temperature settings.""" - query = "What are some creative names for a pet cat?" - - res = perplexity_interface(query, temperature=0.2) - assert isinstance(res, SearchResult) - assert res._value is not None and len(res._value) > 0 - - -def test_perplexity_top_p(perplexity_interface): - """Test Perplexity with top_p parameter.""" - query = "Suggest a good plot for a mystery novel." - res = perplexity_interface(query, top_p=0.6) - assert isinstance(res, SearchResult) - assert res._value is not None and len(res._value) > 0 - - -def test_perplexity_search_domain_filter(perplexity_interface): - """Test Perplexity with search_domain_filter.""" - query = "What is the main idea of Albert Einstein's theory of relativity, from wikipedia.org?" - # Engine default is ["perplexity.ai"], override it. - res = perplexity_interface(query, search_domain_filter=["wikipedia.org"]) - assert isinstance(res, SearchResult) - assert res._value is not None and len(res._value) > 0 - - -def test_perplexity_return_images_parameter_handling(perplexity_interface): - """Test Perplexity's handling of the return_images parameter.""" - query = "Show me pictures of the aurora borealis." - - res_with_images = perplexity_interface(query, return_images=True) - assert isinstance(res_with_images, SearchResult) - assert res_with_images._value is not None # Textual part - assert res_with_images.raw is not None # Full API response - # Actual image data or links would be in res_with_images.raw, format dependent on Perplexity API. - - res_without_images = perplexity_interface(query, return_images=False) - assert isinstance(res_without_images, SearchResult) - assert res_without_images._value is not None - - -def test_perplexity_return_related_questions_parameter_handling(perplexity_interface): - """Test Perplexity's handling of the return_related_questions parameter.""" - query = "What are the benefits of meditation?" - - res_with_related = perplexity_interface(query, return_related_questions=True) - assert isinstance(res_with_related, SearchResult) - assert res_with_related._value is not None # Textual part - assert res_with_related.raw is not None # Full API response - # Related questions, if returned, would be in res_with_related.raw. - - res_without_related = perplexity_interface(query, return_related_questions=False) - assert isinstance(res_without_related, SearchResult) - assert res_without_related._value is not None - - -def test_perplexity_search_recency_filter(perplexity_interface): - """Test Perplexity with search_recency_filter.""" - query = "What are the latest developments in space exploration this week?" - res = perplexity_interface(query, search_recency_filter="week") # Default is "month" - assert isinstance(res, SearchResult) - assert res._value is not None and len(res._value) > 0 - - -def test_perplexity_top_k(perplexity_interface): - """Test Perplexity with top_k parameter.""" - query = "Describe a fantasy creature." - res = perplexity_interface(query, top_k=5) # API default is 0 (disabled) - assert isinstance(res, SearchResult) - assert res._value is not None and len(res._value) > 0 - - -def test_perplexity_presence_penalty(perplexity_interface): - """Test Perplexity with presence_penalty parameter.""" - query = "Summarize the plot of 'Hamlet' ensuring to cover diverse aspects without dwelling on one." - res = perplexity_interface(query, presence_penalty=0.8) # API default is 0 - assert isinstance(res, SearchResult) - assert res._value is not None and len(res._value) > 0 - - -def test_perplexity_frequency_penalty(perplexity_interface): - """Test Perplexity with frequency_penalty parameter.""" - query = "Explain photosynthesis using unique phrasing for each part of the process." - res = perplexity_interface(query, frequency_penalty=1.2) # API default is 1 - assert isinstance(res, SearchResult) - assert res._value is not None and len(res._value) > 0 - - -def test_perplexity_response_format_json(perplexity_interface): - """Test Perplexity with response_format for JSON output using json_schema.""" - - class BasketballPlayerInfo(BaseModel): - first_name: str - last_name: str - year_of_birth: int - num_seasons_in_nba: int - - query = "Tell me about Michael Jordan. Please output a JSON object containing the following fields: first_name, last_name, year_of_birth, num_seasons_in_nba." - system_message = "Be precise and concise." - - res = perplexity_interface( - query, - system_message=system_message, - response_format={ - "type": "json_schema", - "json_schema": {"schema": BasketballPlayerInfo.model_json_schema()} - } - ) - - assert isinstance(res, SearchResult) - assert res._value is not None and len(res._value) > 0 - - raw_content = res.raw['choices'][0]['message']['content'] - try: - json_output = json.loads(raw_content) - assert isinstance(json_output, dict), f"Expected JSON object, got {type(json_output)}" - # Validate the schema structure - assert "first_name" in json_output, "Missing 'first_name' field in response" - assert "last_name" in json_output, "Missing 'last_name' field in response" - assert "year_of_birth" in json_output, "Missing 'year_of_birth' field in response" - assert "num_seasons_in_nba" in json_output, "Missing 'num_seasons_in_nba' field in response" - # Validate data types - assert isinstance(json_output["first_name"], str), "first_name should be a string" - assert isinstance(json_output["last_name"], str), "last_name should be a string" - assert isinstance(json_output["year_of_birth"], int), "year_of_birth should be an integer" - assert isinstance(json_output["num_seasons_in_nba"], int), "num_seasons_in_nba should be an integer" - # Validate expected values - assert json_output["first_name"] == "Michael", "Incorrect first_name value" - assert json_output["last_name"] == "Jordan", "Incorrect last_name value" - except json.JSONDecodeError: - pytest.fail(f"Response content was not valid JSON as expected. Raw content: {raw_content}") - except Exception as e: - pytest.fail(f"Error processing JSON response: {e}. Raw content: {raw_content}") - - -def test_perplexity_response_format_regex(perplexity_interface): - """Test Perplexity with response_format using regex pattern matching.""" - - query = "What is the IPv4 address of OpenDNS DNS server?" - system_message = "Be precise and concise." - - ipv4_regex = r"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" - - response_format = { - "type": "regex", - "regex": {"regex": ipv4_regex} - } - - res = perplexity_interface(query, system_message=system_message, response_format=response_format) - - assert isinstance(res, SearchResult) - assert res._value is not None, "Response value should not be None" - assert len(res._value) > 0, "Response value should not be empty" - - ipv4_pattern = re.compile(ipv4_regex) - assert ipv4_pattern.fullmatch(res._value.strip()), f"Response '{res._value}' does not match IPv4 pattern" - - -def test_perplexity_web_search_options(perplexity_interface): - """Test Perplexity with web_search_options.""" - query = "What are some recent breakthroughs in AI research?" - web_search_opts = { - "search_context_size": "high", # Options: low, medium, high - "user_location": {"country": "CA"} # Example: Filter by country - } - res = perplexity_interface(query, web_search_options=web_search_opts) - assert isinstance(res, SearchResult) - assert res._value is not None and len(res._value) > 0 diff --git a/symbolicai-main/symbolicai-main/tests/functional/test_apply_postprocess.py b/symbolicai-main/symbolicai-main/tests/functional/test_apply_postprocess.py deleted file mode 100644 index 0426920a6fc33141d26cdf89fdbe2e6102568774..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/functional/test_apply_postprocess.py +++ /dev/null @@ -1,183 +0,0 @@ -from typing import Any - -import pytest - -from symai.functional import (ConstraintViolationException, - ProbabilisticBooleanMode, _apply_postprocessors) -from symai.post_processors import PostProcessor - - -# Mock classes and functions -class MockArgument: - def __init__(self): - self.prop = MockProp() - - -class MockProp: - def __init__(self): - self.constraints = [] - self.outputs = None - self.metadata = None - self.raw_output = None - self.preview = False - - -class MockPostProcessor(PostProcessor): - def __call__(self, rsp: Any, argument: Any) -> Any: - return rsp.upper() - - -class MockPostProcessor1(PostProcessor): - def __call__(self, rsp: Any, argument: Any) -> Any: - return rsp.upper() - - -class MockPostProcessor2(PostProcessor): - def __call__(self, rsp: Any, argument: Any) -> Any: - return rsp + " world" - - -def always_true(x): - return True - - -def always_false(x): - return False - -# Test cases -def test_postprocess_response_basic(): - rsp = ["hello"] - return_constraint = str - post_processors = None - argument = MockArgument() - argument.prop.outputs = (rsp, None) - mode = ProbabilisticBooleanMode.MEDIUM - - result, metadata = _apply_postprocessors(argument.prop.outputs, return_constraint, post_processors, argument, mode) - assert result == "hello" - assert metadata is None - - -def test_postprocess_response_with_post_processor(): - rsp = ["hello"] - return_constraint = str - post_processors = [MockPostProcessor()] - argument = MockArgument() - argument.prop.outputs = (rsp, None) - mode = ProbabilisticBooleanMode.MEDIUM - - result, metadata = _apply_postprocessors(argument.prop.outputs, return_constraint, post_processors, argument, mode) - assert result == "HELLO" - assert metadata is None - - -def test_postprocess_response_with_constraint_satisfied(): - rsp = ["hello"] - return_constraint = str - post_processors = None - argument = MockArgument() - argument.prop.constraints = [always_true] - argument.prop.outputs = (rsp, None) - mode = ProbabilisticBooleanMode.MEDIUM - - result, metadata = _apply_postprocessors(argument.prop.outputs, return_constraint, post_processors, argument, mode) - assert result == "hello" - assert metadata is None - - -def test_postprocess_response_with_constraint_violation(): - rsp = ["hello"] - return_constraint = str - post_processors = None - argument = MockArgument() - argument.prop.constraints = [always_false] - argument.prop.outputs = (rsp, None) - mode = ProbabilisticBooleanMode.MEDIUM - - with pytest.raises(ConstraintViolationException): - _apply_postprocessors(argument.prop.outputs, return_constraint, post_processors, argument, mode) - - -def test_postprocess_response_type_casting(): - rsp = ["42"] - return_constraint = int - post_processors = None - argument = MockArgument() - argument.prop.outputs = (rsp, None) - mode = ProbabilisticBooleanMode.MEDIUM - - result, metadata = _apply_postprocessors(argument.prop.outputs, return_constraint, post_processors, argument, mode) - assert result == 42 - assert isinstance(result, int) - assert metadata is None - - -def test_postprocess_response_with_multiple_post_processors(): - rsp = ["hello"] - return_constraint = str - post_processors = [MockPostProcessor1(), MockPostProcessor2()] - argument = MockArgument() - argument.prop.outputs = (rsp, None) - mode = ProbabilisticBooleanMode.MEDIUM - - result, metadata = _apply_postprocessors(argument.prop.outputs, return_constraint, post_processors, argument, mode) - assert result == "HELLO world" - assert metadata is None - - -def test_postprocess_response_with_multiple_constraints(): - rsp = ["hello"] - return_constraint = str - post_processors = None - argument = MockArgument() - argument.prop.constraints = [always_true, always_true] - argument.prop.outputs = (rsp, None) - mode = ProbabilisticBooleanMode.MEDIUM - - result, metadata = _apply_postprocessors(argument.prop.outputs, return_constraint, post_processors, argument, mode) - assert result == "hello" - assert metadata is None - - -def test_postprocess_response_with_mixed_constraints(): - rsp = ["hello"] - return_constraint = str - post_processors = None - argument = MockArgument() - argument.prop.constraints = [always_true, always_false] - argument.prop.outputs = (rsp, None) - mode = ProbabilisticBooleanMode.MEDIUM - - with pytest.raises(ConstraintViolationException): - _apply_postprocessors(argument.prop.outputs, return_constraint, post_processors, argument, mode) - - -def test_postprocess_response_with_list_return_constraint(): - rsp = [["a", "b", "c"]] - return_constraint = list - post_processors = None - argument = MockArgument() - argument.prop.outputs = (rsp, None) - mode = ProbabilisticBooleanMode.MEDIUM - - result, metadata = _apply_postprocessors(argument.prop.outputs, return_constraint, post_processors, argument, mode) - assert result == ["a", "b", "c"] - assert isinstance(result, list) - assert metadata is None - - -def test_postprocess_response_with_preview_mode(): - outputs_tuple = (["hello"], {"some_meta": "data"}) - return_constraint = int # This should be ignored in preview mode - post_processors = [MockPostProcessor()] # This should be ignored - argument = MockArgument() - argument.prop.outputs = outputs_tuple - argument.prop.preview = True - argument.prop.constraints = [always_false] # This should be ignored - - outputs_param_to_function = (["raw_input_string"], {"meta": "info"}) - - result = _apply_postprocessors(outputs_param_to_function, return_constraint, post_processors, argument, ProbabilisticBooleanMode.MEDIUM) - - # In preview mode, the function should return the `outputs` argument directly. - assert result == outputs_param_to_function diff --git a/symbolicai-main/symbolicai-main/tests/functional/test_apply_preprocessors.py b/symbolicai-main/symbolicai-main/tests/functional/test_apply_preprocessors.py deleted file mode 100644 index 3f6d2483342adb9993e8b6a1bd8099a75ed0c035..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/functional/test_apply_preprocessors.py +++ /dev/null @@ -1,70 +0,0 @@ -from types import SimpleNamespace - -import pytest - -from symai.functional import _apply_preprocessors -from symai.pre_processors import PreProcessor - - -class MockArgument: - def __init__(self, raw_input=False, args=None, instance=""): - self.prop = SimpleNamespace(raw_input=raw_input, instance=instance) - self.args = args or [] - -class MockPreProcessor(PreProcessor): - def __call__(self, argument): - return f"Processed: {argument.prop.instance}" - -@pytest.mark.parametrize("raw_input,args,pre_processors,instance,expected", [ - (False, [], [MockPreProcessor()], "test_instance", "Processed: test_instance"), - (True, ["arg1", "test_instance"], None, "test_instance", "arg1 test_instance"), - (False, [], None, "test_instance", ""), - (False, ["arg1", "arg2"], None, "test_instance", "arg1 arg2"), - (False, ["test prompt"], [], "test_instance", "test prompt"), -]) -def test_apply_preprocessors(raw_input, args, pre_processors, instance, expected): - argument = MockArgument(raw_input=raw_input, args=args) - result = _apply_preprocessors(argument, instance, pre_processors) - assert result == expected - -def test_apply_preprocessors_multiple(): - class AnotherMockPreProcessor(PreProcessor): - def __call__(self, argument): - return f"Also processed: {argument.prop.instance}" - - argument = MockArgument(raw_input=False) - pre_processors = [MockPreProcessor(), AnotherMockPreProcessor()] - result = _apply_preprocessors(argument, "test_instance", pre_processors) - assert result == "Processed: test_instanceAlso processed: test_instance" - -def test_apply_preprocessors_none_return(): - class NoneReturnPreProcessor(PreProcessor): - def __call__(self, argument): - return None - - argument = MockArgument(raw_input=False) - pre_processors = [NoneReturnPreProcessor(), MockPreProcessor()] - result = _apply_preprocessors(argument, "test_instance", pre_processors) - assert result == "Processed: test_instance" - -def test_apply_preprocessors_modifying(): - class ModifyingPreProcessor(PreProcessor): - def __call__(self, argument): - argument.prop.instance = "modified_" + argument.prop.instance - return argument.prop.instance - - argument = MockArgument(raw_input=False, instance="test_instance") - pre_processors = [ModifyingPreProcessor(), MockPreProcessor()] - result = _apply_preprocessors(argument, "test_instance", pre_processors) - assert result == "modified_test_instanceProcessed: modified_test_instance" - - -def test_apply_preprocessors_exception(): - class ExceptionPreProcessor(PreProcessor): - def __call__(self, argument): - raise ValueError("Test exception") - - argument = MockArgument(raw_input=False) - pre_processors = [ExceptionPreProcessor(), MockPreProcessor()] - with pytest.raises(ValueError, match="Test exception"): - _apply_preprocessors(argument, "test_instance", pre_processors) diff --git a/symbolicai-main/symbolicai-main/tests/functional/test_execute_query_fallback.py b/symbolicai-main/symbolicai-main/tests/functional/test_execute_query_fallback.py deleted file mode 100644 index d2e300884b94edbc27fb2e5b68f7f651de3dc887..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/functional/test_execute_query_fallback.py +++ /dev/null @@ -1,159 +0,0 @@ -import pytest -from box import Box - -from symai import Symbol -from symai.core import Argument -from symai.functional import _execute_query, _execute_query_fallback - - -def test_successful_execution(): - def test_func(instance, error, stack_trace, x, y): - return x + y - - argument = Argument( - args=(), - signature_kwargs={ - 'x': 3, - 'y': 4 - }, - decorator_kwargs={} - ) - instance = None - result = _execute_query_fallback(func=test_func, instance=instance, argument=argument, error=None, stack_trace=None) - assert result['data'] == 7 - assert result['error'] is None - assert result['stack_trace'] is None - -def test_return_none_with_default(): - def test_func(instance=None, argument=None, error=None, stack_trace=None): - return None - - # Create an Argument object with the proper structure - argument = Argument( - args=(), - signature_kwargs={}, - decorator_kwargs={'default': "default_value"} - ) - - result = _execute_query_fallback(test_func, None, argument, "error_obj", "stack_trace_obj") - - assert result['data'] == "default_value" - assert result['error'] == "error_obj" - assert result['stack_trace'] == "stack_trace_obj" - -def test_return_value_with_error_info(): - def test_func(instance, error, stack_trace): - return "success_value" # Function returns non-None value - - error_obj = ValueError("Test error") - stack_trace = "mock stack trace" - - # Create a proper Argument object - argument = Argument( - args=(), - signature_kwargs={}, - decorator_kwargs={} - ) - - result = _execute_query_fallback(test_func, None, argument, error_obj, stack_trace) - - assert result['data'] == "success_value" - assert result['error'] == error_obj - assert result['stack_trace'] == stack_trace - -def test_exception_without_default(): - def test_func(instance, error, stack_trace): - return None # Function returns None - - error_obj = ValueError("Test error") - - argument = Argument( - args=(), - signature_kwargs={}, - decorator_kwargs={} # No default value specified - ) - - with pytest.raises(ValueError) as excinfo: - _execute_query_fallback(test_func, None, argument, error_obj, None) - assert excinfo.value == error_obj - -def test_with_instance_and_kwargs(): - def test_func(instance, error, stack_trace, x, y): - return instance.value + x + y - - class DummyInstance: - value = 5 - - argument = Argument( - args=(), # x=3 as positional argument - signature_kwargs={'y': 7, 'x':3}, # Override default y value - decorator_kwargs={} - ) - - result = _execute_query_fallback(test_func, DummyInstance(), argument, None, None) - assert result['data'] == 15 # 5 (instance.value) + 3 (x) + 7 (y) = 15 - -def test_different_default_types(): - def test_func(instance, error, stack_trace): - return None # Function returns None, so default is used - - # Test with various default types - for default_value in [42, [1, 2, 3], {"a": 1}]: - # Create a proper Argument object with default value - argument = Argument( - args=(), - signature_kwargs={}, - decorator_kwargs={'default': default_value} - ) - - result = _execute_query_fallback(test_func, None, argument, "error", "trace") - - assert result['data'] == default_value - assert result['error'] == "error" - assert result['stack_trace'] == "trace" - - -def test_empty_args_kwargs(): - def test_func(instance, error, stack_trace): - return "Success" - - argument = Argument( - args=(), - signature_kwargs={}, - decorator_kwargs={} - ) - - result = _execute_query_fallback(test_func, None, argument, None, None) - assert result['data'] == "Success" - - -def test_symbol_query_with_preview_true(): - original_symbol_text = "This is a test Symbol for preview functionality." - query_context = "What is the nature of this symbol?" - - sym = Symbol(original_symbol_text) - preview_symbol = sym.query(query_context, preview=True) - - assert isinstance(preview_symbol, Symbol), \ - "The result of a preview query should still be a Symbol." - - preview_value = preview_symbol.value - assert isinstance(preview_value, Box), \ - f"The .value of the preview Symbol should be a Box, got {type(preview_value)} instead." - assert 'args' in preview_value, "Preview Box should contain 'args'" - assert 'signature_kwargs' in preview_value, "Preview Box should contain 'signature_kwargs'" - assert 'decorator_kwargs' in preview_value, "Preview Box should contain 'decorator_kwargs'" - assert 'kwargs' in preview_value, "Preview Box should contain 'kwargs'" - assert 'prop' in preview_value, "Preview Box should contain 'prop' (metadata)" - - decorator_kwargs = preview_value['decorator_kwargs'] - assert decorator_kwargs.get('preview') is True, \ - "decorator_kwargs should explicitly state preview is True." - assert decorator_kwargs.get('context') == query_context, \ - "decorator_kwargs should contain the original query context." - assert 'prompt' in decorator_kwargs, "decorator_kwargs should contain 'prompt'" - assert 'examples' in decorator_kwargs, "decorator_kwargs should contain 'examples'" - - # Also check that the original symbol on which query was called remains unchanged - assert sym.value == original_symbol_text, \ - "The original symbol's value should not be altered by a preview query." diff --git a/symbolicai-main/symbolicai-main/tests/functional/test_limit_num_outputs.py b/symbolicai-main/symbolicai-main/tests/functional/test_limit_num_outputs.py deleted file mode 100644 index 8634acc75e6a6d66d6bbd83064f190f5090b8c95..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/functional/test_limit_num_outputs.py +++ /dev/null @@ -1,82 +0,0 @@ -from types import SimpleNamespace - -import pytest - -from symai.functional import _limit_number_results - - -@pytest.fixture -def argument(): - arg = SimpleNamespace() - arg.prop = SimpleNamespace() - return arg - -class TestLimitNumberResults: - def test_string_list_limit(self, argument): - argument.prop.limit = 2 - rsp = ['a', 'b', 'c'] - result = _limit_number_results(rsp, argument, str) - assert result == 'a\nb' - - def test_list_limit(self, argument): - argument.prop.limit = 2 - rsp = [1, 2, 3, 4] - result = _limit_number_results(rsp, argument, list) - assert result == [1, 2] - - def test_dict_limit(self, argument): - argument.prop.limit = 2 - rsp = {'a': 1, 'b': 2, 'c': 3} - result = _limit_number_results(rsp, argument, dict) - assert result == {'a': 1, 'b': 2} - - def test_set_limit(self, argument): - argument.prop.limit = 2 - rsp = {1, 2, 3, 4} - result = _limit_number_results(rsp, argument, set) - assert len(result) == 2 - assert all(x in {1, 2, 3, 4} for x in result) - - def test_tuple_limit(self, argument): - argument.prop.limit = 2 - rsp = (1, 2, 3, 4) - result = _limit_number_results(rsp, argument, tuple) - assert result == (1, 2) - - def test_no_limit(self, argument): - argument.prop.limit = None - rsp = [1, 2, 3, 4] - result = _limit_number_results(rsp, argument, list) - assert result == [1, 2, 3, 4] - - def test_limit_greater_than_length(self, argument): - argument.prop.limit = 10 - rsp = [1, 2, 3] - result = _limit_number_results(rsp, argument, list) - assert result == [1, 2, 3] - - def test_non_iterable_input(self, argument): - argument.prop.limit = 2 - rsp = 42 - result = _limit_number_results(rsp, argument, int) - assert result == 42 - - def test_limit_of_one(self, argument): - argument.prop.limit = 1 - rsp = [1, 2, 3] - result = _limit_number_results(rsp, argument, list) - assert result == [1] - - def test_empty_input(self, argument): - argument.prop.limit = 2 - rsp = [] - result = _limit_number_results(rsp, argument, list) - assert result == [] - - def test_string_input(self, argument): - argument.prop.limit = 3 - rsp = "hello" - result = _limit_number_results(rsp, argument, str) - assert result == "hello" - - \ No newline at end of file diff --git a/symbolicai-main/symbolicai-main/tests/functional/test_typecasting.py b/symbolicai-main/symbolicai-main/tests/functional/test_typecasting.py deleted file mode 100644 index 338a0f221ab7fb1146e6ccf09ed7096d6028a22c..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/functional/test_typecasting.py +++ /dev/null @@ -1,124 +0,0 @@ -import inspect -from typing import Any, Dict, List, Type, Union - -import pytest - -from symai.functional import (ConstraintViolationException, - ProbabilisticBooleanMode, _cast_return_type) - - -@pytest.mark.parametrize("rsp, return_constraint, expected_output", [ - # String tests - ("test", str, "test"), - (42, str, "42"), - - # Integer tests - ("42", int, 42), - (42, int, 42), - - # Float tests - ("3.14", float, 3.14), - (3.14, float, 3.14), - - # List tests - ("[1, 2, 3]", list, [1, 2, 3]), - ("['a', 'b', 'c']", list, ['a', 'b', 'c']), - ([1, 2, 3], list, [1, 2, 3]), - - # Tuple tests - ("(1, 2, 3)", tuple, (1, 2, 3)), - ("('a', 'b', 'c')", tuple, ('a', 'b', 'c')), - ((1, 2, 3), tuple, (1, 2, 3)), - - # Set tests - ("{1, 2, 3}", set, {1, 2, 3}), - ("{'a', 'b', 'c'}", set, {'a', 'b', 'c'}), - ({1, 2, 3}, set, {1, 2, 3}), - - # Dict tests - ('{"a": 1, "b": 2}', dict, {"a": 1, "b": 2}), - ({"a": 1, "b": 2}, dict, {"a": 1, "b": 2}), - - # Boolean tests - ("True", bool, True), - ("False", bool, False), - ("1", bool, True), - ("0", bool, False), - (True, bool, True), - (False, bool, False), - -]) -def test_cast_return_type(rsp: Any, return_constraint: Type, expected_output: Any): - result = _cast_return_type(rsp, return_constraint, ProbabilisticBooleanMode.TOLERANT) - assert result == expected_output - assert isinstance(result, return_constraint) - -def test_cast_return_type_empty(): - result = _cast_return_type("test", inspect._empty, ProbabilisticBooleanMode.TOLERANT) - assert result == "test" - -@pytest.mark.parametrize("invalid_input, return_constraint", [ - ("not a list", list), - ("not a tuple", tuple), - ("not a set", set), - ("not a dict", dict), -]) -def test_cast_return_type_invalid_input(invalid_input, return_constraint): - with pytest.warns(UserWarning): - result = _cast_return_type(invalid_input, return_constraint, ProbabilisticBooleanMode.TOLERANT) - assert result == invalid_input - -@pytest.mark.parametrize("empty_input, return_constraint, expected", [ - ("", bool, False), - ([], bool, False), - ({}, bool, False), - (set(), bool, False), -]) -def test_cast_return_type_empty_bool(empty_input, return_constraint, expected): - result = _cast_return_type(empty_input, return_constraint, ProbabilisticBooleanMode.TOLERANT) - assert result == expected - -@pytest.mark.parametrize("input_value, mode, expected", [ - ("yes", ProbabilisticBooleanMode.STRICT, False), - ("true", ProbabilisticBooleanMode.STRICT, True), - ("yes", ProbabilisticBooleanMode.MEDIUM, True), - ("1", ProbabilisticBooleanMode.MEDIUM, False), - ("maybe", ProbabilisticBooleanMode.TOLERANT, False), - ("no", ProbabilisticBooleanMode.TOLERANT, False), -]) -def test_cast_return_type_bool_modes(input_value, mode, expected): - result = _cast_return_type(input_value, bool, mode) - assert result == expected - -def test_cast_return_type_custom_class(): - class CustomClass: - def __init__(self, value): - self.value = value - - result = _cast_return_type("42", CustomClass, ProbabilisticBooleanMode.TOLERANT) - assert isinstance(result, CustomClass) - assert result.value == "42" - -@pytest.mark.parametrize("input_value, return_constraint", [ - (42, str), - ("42", int), - (3.14, int), - ([1, 2, 3], str), - ("['not', 'a', 'list']", list), -]) -def test_cast_return_type_type_conversion(input_value, return_constraint): - result = _cast_return_type(input_value, return_constraint, ProbabilisticBooleanMode.TOLERANT) - assert isinstance(result, return_constraint) - -def test_cast_return_type_none(): - result = _cast_return_type(None, str, ProbabilisticBooleanMode.TOLERANT) - assert result == "None" - -def test_cast_return_type_invalid_mode(): - with pytest.raises(ValueError): - _cast_return_type("yes", bool, "INVALID_MODE") - -def test_cast_return_type_constraint_violation(): - with pytest.raises(ConstraintViolationException): - _cast_return_type("not an int", int, ProbabilisticBooleanMode.STRICT) - diff --git a/symbolicai-main/symbolicai-main/tests/test_components.py b/symbolicai-main/symbolicai-main/tests/test_components.py deleted file mode 100644 index 652ae67b662b836431eee45d218d9123a27f72df..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/test_components.py +++ /dev/null @@ -1,138 +0,0 @@ -import os -import time - -import pytest - -from symai import Expression, PrimitiveDisabler, Symbol -from symai.backend.mixin import OPENAI_CHAT_MODELS, OPENAI_REASONING_MODELS -from symai.backend.settings import SYMAI_CONFIG -from symai.components import DynamicEngine, MetadataTracker -from symai.extended import Interface -from symai.functional import EngineRepository -from symai.symbol import Metadata -from symai.utils import RuntimeInfo - -NEUROSYMBOLIC_ENGINE = SYMAI_CONFIG.get('NEUROSYMBOLIC_ENGINE_MODEL', '') in OPENAI_CHAT_MODELS + OPENAI_REASONING_MODELS -SEARCH_ENGINE = SYMAI_CONFIG.get('SEARCH_ENGINE_MODEL', '') in OPENAI_CHAT_MODELS + OPENAI_REASONING_MODELS - - -def estimate_cost(info: RuntimeInfo, pricing: dict) -> float: - input_cost = (info.prompt_tokens - info.cached_tokens) * pricing.get("input", 0) - cached_input_cost = info.cached_tokens * pricing.get("cached_input", 0) - output_cost = info.completion_tokens * pricing.get("output", 0) - call_cost = info.total_calls * pricing.get("calls", 0) - return input_cost + cached_input_cost + output_cost + call_cost - - -@pytest.mark.skipif(not NEUROSYMBOLIC_ENGINE and not SEARCH_ENGINE, reason="Tested only for OpenAI backend for now.") -def test_metadata_tracker_with_runtimeinfo(): - sym = Symbol("You're supposed to go off the rails and say something pretty crazy.") - search = Interface('openai_search') - start_time = time.perf_counter() - with MetadataTracker() as tracker: - res = sym.query("What is the meaning of life?") - search_res = search("What is the meaning of life?") - end_time = time.perf_counter() - assert res.value is not None and search_res.value is not None, "Expected some non-None output from the query." - - pricing = { - ("GPTXChatEngine", "gpt-4.1"): { - "input": 2. / 1e6, - "cached_input": 0.5 / 1e6, - "output": 8. / 1e6 - }, - ("GPTXSearchEngine", "gpt-4.1-mini"): { - "input": 0.40 / 1e6, - "cached_input": 0.10 / 1e6, - "output": 1.6 / 1e6, - "calls": 27.5 / 1e3 - } - } - - usage_per_engine = RuntimeInfo.from_tracker(tracker, 0) - # total_elapsed_time, prompt_tokens, completion_tokens, reasoning_tokens, cached_tokens, total_calls, total_tokens, cost_estimate - usage = RuntimeInfo(0, 0, 0, 0, 0, 0, 0, 0) - for (engine_name, model_name), data in usage_per_engine.items(): - usage += RuntimeInfo.estimate_cost(data, estimate_cost, pricing=pricing[(engine_name, model_name)]) - # Add total elapsed time to the actual elapsed time - usage.total_elapsed_time = end_time - start_time - - assert usage.total_elapsed_time > 0, "Expected elapsed time to be greater than 0." - assert usage.prompt_tokens > 0, "Expected prompt tokens to be greater than 0." - assert usage.completion_tokens > 0, "Expected completion tokens to be greater than 0." - assert usage.total_tokens > 0, "Expected total tokens to be greater than 0." - assert usage.cost_estimate > 0, "Expected cost estimate to be greater than 0." - assert usage.cached_tokens == 0, "Expected cached tokens to be 0." - assert usage.reasoning_tokens == 0, "Expected reasoning tokens to be 0." - assert usage.total_calls == 2, "Expected total_calls to be 2 (one for query, one for search)." - - -def test_disable_primitives(): - sym1 = Symbol("This is a test") - sym2 = Symbol("This is another test") - sym3 = Expression("This is a test") - - with PrimitiveDisabler(): - # disable primitives - assert all([ - sym1.query('Is this a test?') is None, - sym2.query('Is this a test?') is None, - sym3.query('Is this a test?') is None, - ]) - - # re-enable primitives - assert all([ - sym1.query('Is this a test?') is not None, - sym2.query('Is this a test?') is not None, - sym3.query('Is this a test?') is not None, - ]) - - -def test_dynamic_engine_switching(): - # Fetch API keys from environment variables: - openai_api_key = os.environ.get("OPENAI_API_KEY") - anthropic_api_key = os.environ.get("ANTHROPIC_API_KEY") - - if openai_api_key is None or anthropic_api_key is None: - raise EnvironmentError( - "Missing environment variables: OPENAI_API_KEY and/or ANTHROPIC_API_KEY" - ) - - dynamic_engine1 = DynamicEngine('o1', openai_api_key) - dynamic_engine2 = DynamicEngine('claude-3-5-sonnet-latest', anthropic_api_key) - - # Test with dynamic_engine1 - with dynamic_engine1: - # EngineRepository.get should return the engine_instance from dynamic_engine1 - engine_in_context = EngineRepository.get('neurosymbolic') - assert engine_in_context is dynamic_engine1.engine_instance, \ - "Should use dynamic_engine1 inside its context." - - # Simple check that the Symbol query does not return None - resp1 = Symbol("You are an OpenAI model. " - "You have to tell which model you are specifically." - ).query("Which model are you?") - assert resp1 is not None, \ - "Expected some non-None output from dynamic engine 1 within its context." - - # Once we're outside the dynamic_engine1 context, it should revert to default or another engine - outside_engine1 = EngineRepository.get('neurosymbolic') - assert outside_engine1 != dynamic_engine1.engine_instance, \ - "Should revert to a different engine outside dynamic_engine1 context." - - # Test with dynamic_engine2 - with dynamic_engine2: - engine_in_context = EngineRepository.get('neurosymbolic') - assert engine_in_context is dynamic_engine2.engine_instance, \ - "Should use dynamic_engine2 inside its context." - - resp2 = Symbol("You are an OpenAI model. " - "You have to tell which model you are specifically." - ).query("Which model are you?") - assert resp2 is not None, \ - "Expected some non-None output from dynamic engine 2 within its context." - - # Outside of dynamic_engine2 context, it again reverts - outside_engine2 = EngineRepository.get('neurosymbolic') - assert outside_engine2 != dynamic_engine2.engine_instance, \ - "Should revert to a different engine outside dynamic_engine2 context." diff --git a/symbolicai-main/symbolicai-main/tests/test_imports.py b/symbolicai-main/symbolicai-main/tests/test_imports.py deleted file mode 100644 index 4acfa29c57a254359e1cad73e352c5180c72fd5b..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/test_imports.py +++ /dev/null @@ -1,81 +0,0 @@ -import importlib -import os -import sys -from pathlib import Path - -import pytest - -mandatory_dependencies = [ - "attrs", - "setuptools", - "toml", - "natsort", - "numpy", - "tqdm", - "box", - "pandas", - "sklearn", - "torch", - "torchaudio", - "torchvision", - "yaml", - "transformers", - "sympy", - "openai", - "anthropic", - "pypdf", - "IPython", - "accelerate", - "sentencepiece", - "sentence_transformers", - "tiktoken", - "tika", - "bs4", - "colorama", - "git", - "pathos", - "prompt_toolkit", - "pydub", - "cv2", - "pymongo", - "requests_toolbelt", - "pyvis", - "beartype", - "pydantic", - "pydantic_core", - "pydantic_settings", - "Crypto", -] - -optional_dependencies = { - "bitsandbytes": ["bitsandbytes"], - "blip2": ["decord", "lavis", "cv2"], - "hf": ["transformers", "accelerate", "peft", "datasets", "trl"], - "wolframalpha": ["wolframalpha"], - "whisper": ["whisper"], - "selenium": ["selenium", "webdriver_manager", "chromedriver_autoinstaller"], - "serpapi": ["serpapi"], - "pinecone": ["pinecone"], - "bard": ["bardapi"], - "services": ["fastapi", "redis", "uvicorn"], - "solver": ["z3"], -} - -@pytest.mark.parametrize("module_name", mandatory_dependencies) -def test_mandatory_dependencies(module_name): - importlib.import_module(module_name) - -@pytest.mark.parametrize("group, modules", optional_dependencies.items()) -def test_optional_dependencies(group, modules): - for module_name in modules: - try: - importlib.import_module(module_name) - except pytest.fail.Exception: - assert False, f"Optional dependency {module_name} from group {group} is not installed" - -def test_symai(): - try: - importlib.import_module("symai") - except pytest.fail.Exception: - assert False, "Failed to import symai" - diff --git a/symbolicai-main/symbolicai-main/tests/test_misc.py b/symbolicai-main/symbolicai-main/tests/test_misc.py deleted file mode 100644 index f4c381d32247bc11d64d6c48553f137ba0dba1d8..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/test_misc.py +++ /dev/null @@ -1,131 +0,0 @@ -import json -import re -import sys -import time - -import psutil -import pytest - -from symai import Expression, Symbol -from symai.backend.settings import SYMAI_CONFIG -from symai.components import FileReader -from symai.formatter.formatter import CHUNK_REGEX -from symai.utils import format_bytes - -NEUROSYMBOLIC = SYMAI_CONFIG.get('NEUROSYMBOLIC_ENGINE_MODEL') -CLAUDE_THINKING = {"budget_tokens": 1024} -CLAUDE_MAX_TOKENS = 4092 # Limit this, otherwise: "ValueError: Streaming is strongly recommended for operations that may take longer than 10 minutes." - -@pytest.mark.mandatory -@pytest.mark.skipif(NEUROSYMBOLIC.startswith('llama'), reason='llamacpp JSON format not yet supported') -@pytest.mark.skipif(NEUROSYMBOLIC.startswith('huggingface'), reason='huggingface JSON format not yet supported') -def test_json_format(): - admin_role = 'system' if \ - (NEUROSYMBOLIC.startswith('gpt') or - NEUROSYMBOLIC.startswith('claude') or - NEUROSYMBOLIC.startswith('gemini')) \ - else 'developer' - if all(id not in NEUROSYMBOLIC for id in ['3-7', '4-0']): - res = Expression.prompt( - message=[ - {"role": admin_role, "content": "You are a helpful assistant designed to output JSON."}, - {"role": "user", "content": "Who won the world series in 2020? Return the answer in the following format: { 'team': 'str', 'year': 'int', 'coach': 'str'}}"} - ], - response_format={ "type": "json_object" }, - suppress_verbose_output=True - ) - else: - res = Expression.prompt( - message=[ - {"role": admin_role, "content": "You are a helpful assistant designed to output JSON."}, - {"role": "user", "content": "Who won the world series in 2020? Return the answer in the following format: { 'team': 'str', 'year': 'int', 'coach': 'str'}}"} - ], - response_format={ "type": "json_object" }, - suppress_verbose_output=True, - max_tokens=CLAUDE_MAX_TOKENS, - thinking=CLAUDE_THINKING - ) - - target = {'team': 'Los Angeles Dodgers', 'year': 2020, 'coach': 'Dave Roberts'} - res = json.loads(res.value) - assert res == target - -@pytest.mark.mandatory -def test_fill_format(): - text = ''' -Oscar-winning actress Anne Hathaway has said that she had to kiss a series of actors during the audition process in the 2000s to “test for chemistry” on camera. - -Now 41 and with dozens of movies to her name, Hathaway has revealed how early on in her career she went along with the “gross” request to “make out” with male actors to test their suitability for an unnamed movie. - -{{fill}} - -Speaking to V Magazine in an interview published Monday, Hathaway said: “Back in the 2000s — and this did happen to me — it was considered normal to ask an actor to make out with other actors to test for chemistry. Which is actually the worst way to do it. -''' - S = Symbol(text) - if all(id not in NEUROSYMBOLIC for id in ['3-7', '4-0']): - res = S.query("Fill in the text.", template_suffix="{{fill}}") - else: - res = S.query("Fill in the text.", template_suffix="{{fill}}", max_tokens=CLAUDE_MAX_TOKENS, thinking=CLAUDE_THINKING) - assert "{{fill}}" not in S.value.replace("{{fill}}", res.value) - -@pytest.mark.mandatory -def test_self_prompt(): - if all(id not in NEUROSYMBOLIC for id in ['3-7', '4-0']): - sym = Symbol('np.log2(2)', self_prompt=True) - res = Symbol('np.log2(2)').query('Is this equal to 1?', self_prompt=True) - else: - sym = Symbol('np.log2(2)', self_prompt=True, max_tokens=CLAUDE_MAX_TOKENS, thinking=CLAUDE_THINKING, suppress_verbose_output=True) - res = Symbol('np.log2(2)').query('Is this equal to 1?', self_prompt=True, max_tokens=CLAUDE_MAX_TOKENS, thinking=CLAUDE_THINKING, suppress_verbose_output=True) - assert any(s in res.value.lower() for s in ['yes', 'correct', 'true']) - -def test_regex_format(): - # Test the regex pattern - reader = FileReader() - - # Read from the arg[1] file - test_text = reader('README.md') - - # Start measuring time and memory - start_time = time.time() - start_memory = psutil.Process().memory_info().rss - - # Apply the regex - matches = CHUNK_REGEX.findall(str(test_text)) - - # End measuring time and memory - end_time = time.time() - end_memory = psutil.Process().memory_info().rss - - # Calculate execution time and memory usage - execution_time = end_time - start_time - memory_used = end_memory - start_memory - - # Output results - print(f"Number of chunks: {len(matches) if matches else 0}") - print(f"Execution time: {execution_time:.3f} seconds") - print(f"Memory used: {format_bytes(memory_used)}") - - # Output the first 100 matches (or fewer if there are less than 100) - print('\nFirst 100 chunks:') - if matches: - for match in matches[:100]: - print(repr(match[:50])) - else: - print('No chunks found.') - - # Output regex flags - flags = [] - if CHUNK_REGEX.flags & re.MULTILINE: - flags.append('m') - if CHUNK_REGEX.flags & re.UNICODE: - flags.append('u') - print(f"\nRegex flags: {''.join(flags)}") - - # Check for potential issues - if execution_time > 5: - print('\nWarning: Execution time exceeded 5 seconds. The regex might be too complex or the input too large.') - if memory_used > 100 * 1024 * 1024: - print('\nWarning: Memory usage exceeded 100 MB. Consider processing the input in smaller chunks.') - -if __name__ == "__main__": - pytest.main() diff --git a/symbolicai-main/symbolicai-main/tests/test_primitives.py b/symbolicai-main/symbolicai-main/tests/test_primitives.py deleted file mode 100644 index a515363290bd84548621f5c6143cf8dd4ae607db..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/tests/test_primitives.py +++ /dev/null @@ -1,2315 +0,0 @@ -from __future__ import annotations - -import os -import tempfile -from textwrap import dedent -from typing import Any - -import numpy as np -import pytest - -from symai import Expression, Symbol -from symai.backend.settings import SYMAI_CONFIG - -_C = { - "cyan": "\033[96m", - "green": "\033[92m", - "yellow": "\033[93m", - "reset": "\033[0m", -} - -@pytest.mark.mandatory -def display_op(before: Any, after: Any, op: str, type: str): - def _w(x: Any) -> Any: - return x.value if isinstance(x, Symbol) else x - - print( - f"{_C['cyan']}[ {op} :: {type} ]{_C['reset']} " - f"{_C['yellow']}{_w(before)}{_C['reset']} ➜ " - f"{_C['green']}{_w(after)}{_C['reset']}" - ) - -@pytest.mark.mandatory -def test_syn_sem_pr(): - """Test the CastingPrimitives class methods.""" - - sym_default = Symbol(123) # syntactic by default - assert not sym_default.__semantic__, "default must be syntactic" - - sym_sem = sym_default.sem # convert to semantic - assert sym_sem.__semantic__, ".sem should yield a semantic symbol" - assert sym_sem <= 123 - - sym_syn = sym_sem.syn # convert back to syntactic - assert not sym_syn.__semantic__, ".syn after .sem should revert to syntactic" - assert sym_syn <= 123 - - sym_init_sem = Symbol("hello", semantic=True) - assert sym_init_sem.__semantic__, "explicit semantic=True must set semantic" - - chain = sym_init_sem.syn.sem.syn - assert not chain.__semantic__, "final .syn should leave symbol syntactic" - assert chain == "hello" - - assert isinstance(chain, Symbol) - assert chain == sym_init_sem - - lst = Symbol(["apple", "banana", "cucumber"]).sem.syn.sem # ends semantic - sym = Symbol("fruit") - assert lst.__semantic__ # semantic - assert not sym.__semantic__ # syntactic - assert sym not in lst.syn - assert sym in lst - -@pytest.mark.mandatory -def test_negate_invert_op(): - """Test the OperatorPrimitives class methods.""" - - sym_int_pos = Symbol(5) - display_op(sym_int_pos, -sym_int_pos, "-", "syntactic") - assert -sym_int_pos.value == -5 - - sym_int_neg = Symbol(-12) - display_op(sym_int_neg, -sym_int_neg, "-", "syntactic") - assert -sym_int_neg.value == 12 - - sym_float_pos = Symbol(7.77) - display_op(sym_float_pos, -sym_float_pos, "-", "syntactic") - assert -sym_float_pos.value == -7.77 - - sym_float_neg = Symbol(-0.123) - display_op(sym_float_neg, -sym_float_neg, "-", "syntactic") - assert -sym_float_neg.value == 0.123 - - sym_str_affirmative = Symbol('I am happy.', semantic=True) - display_op(sym_str_affirmative, -sym_str_affirmative, "~", "semantic") - - sym_str_negative = Symbol('This is not correct.', semantic=True) - display_op(sym_str_negative, -sym_str_negative, "~", "semantic") - - sym_bool_true = Symbol(True) - sym_bool_false = Symbol(False) - - assert ~sym_bool_true == False - display_op(f"{sym_bool_true}", ~sym_bool_true, "~", "syntactic") - assert ~sym_bool_false == True - display_op(f"{sym_bool_false}", ~sym_bool_false, "~", "syntactic") - - sym_int_zero = Symbol(0) - sym_int_five = Symbol(5) - sym_int_neg_one = Symbol(-1) - - assert ~sym_int_zero == -1 - display_op(f"{sym_int_zero}", ~sym_int_zero, "~", "syntactic") - assert ~sym_int_five == -6 - display_op(f"{sym_int_five}", ~sym_int_five, "~", "syntactic") - assert ~sym_int_neg_one == 0 - display_op(f"{sym_int_neg_one}", ~sym_int_neg_one, "~", "syntactic") - - sym_positive_statement = Symbol('I am confident.', semantic=True) - sym_negative_statement = Symbol('This is wrong.', semantic=True) - sym_neutral_statement = Symbol('The weather is nice.', semantic=True) - - display_op(f"'{sym_positive_statement}'", ~sym_positive_statement, "~", "semantic") - display_op(f"'{sym_negative_statement}'", ~sym_negative_statement, "~", "semantic") - display_op(f"'{sym_neutral_statement}'", ~sym_neutral_statement, "~", "semantic") - - sym_bool_true_sem = Symbol(True, semantic=True) - sym_bool_false_sem = Symbol(False, semantic=True) - - display_op(f"{sym_bool_true_sem}", ~sym_bool_true_sem, "~", "semantic") - display_op(f"{sym_bool_false_sem}", ~sym_bool_false_sem, "~", "semantic") - - sym_affirmative = Symbol('Yes, absolutely correct.', semantic=True) - sym_denial = Symbol('No, that is incorrect.', semantic=True) - sym_uncertainty = Symbol('Maybe it could work.', semantic=True) - - display_op(f"'{sym_affirmative}'", ~sym_affirmative, "~", "semantic") - display_op(f"'{sym_denial}'", ~sym_denial, "~", "semantic") - display_op(f"'{sym_uncertainty}'", ~sym_uncertainty, "~", "semantic") - - sym_mixed = Symbol('I agree completely.') - display_op(f"'{sym_mixed}'", ~sym_mixed.sem, "~", "semantic") - - sym_mixed_sem = Symbol('This is definitely false.', semantic=True) - display_op(f"'{sym_mixed_sem}'", ~sym_mixed_sem.syn, "~", "syntactic") - -@pytest.mark.mandatory -def test_contains_op(): - """Test the OperatorPrimitives class methods.""" - - sym_str_syn = Symbol('apple banana cherry') - sym_str_sem = Symbol('apple banana cherry', semantic=True) # or can be converted to a semantic symbol with ".sym" method - sym_list_syn = Symbol(['apple', 'banana', 'cherry']) - sym_list_sem = Symbol(['apple', 'banana', 'cherry'], semantic=True) # or can be converted to a semantic symbol with ".sym" method - other1 = Symbol('apple') - other2 = 'fruit' - - assert other1 in sym_str_syn - display_op(f"'{sym_str_syn}' contains '{other1}'", other1 in sym_str_syn, "in", "syntactic") - display_op(f"'{sym_str_sem}' contains '{other2}'", other2 in sym_str_sem, "in", "semantic") - assert other1 in sym_list_syn - display_op(f"'{sym_list_syn}' contains '{other1}'", other1 in sym_list_syn, "in", "syntactic") - display_op(f"'{sym_list_sem}' contains '{other2}'", other2 in sym_list_sem, "in", "semantic") - -@pytest.mark.mandatory -def test_equals_op(): - """Test the OperatorPrimitives class methods.""" - - sym1_syn = Symbol('hello world') - sym2_syn = Symbol('hello world') - sym3_syn = Symbol('goodbye world') - - assert sym1_syn == sym2_syn - display_op(f"'{sym1_syn}' == '{sym2_syn}'", sym1_syn == sym2_syn, "==", "syntactic") - assert not (sym1_syn == sym3_syn) - display_op(f"'{sym1_syn}' == '{sym3_syn}'", sym1_syn == sym3_syn, "==", "syntactic") - - sym_greeting_sem = Symbol('Hello there!', semantic=True) # or can be converted to a semantic symbol with ".sym" method - sym_farewell_sem = Symbol('Goodbye friend!') - greeting_variant = 'Hi there!' - farewell_variant = 'See you later!' - - display_op(f"'{sym_greeting_sem}' == '{greeting_variant}'", sym_greeting_sem == greeting_variant, "==", "semantic") - display_op(f"'{sym_farewell_sem}' == '{farewell_variant}'", sym_farewell_sem == farewell_variant, "==", "semantic") - - sym_num1 = Symbol(42) - sym_num2 = Symbol(42) - sym_num3 = Symbol(24) - - assert sym_num1 == sym_num2 - display_op(f"{sym_num1} == {sym_num2}", sym_num1 == sym_num2, "==", "syntactic") - assert not (sym_num1 == sym_num3) - display_op(f"{sym_num1} == {sym_num3}", sym_num1 == sym_num3, "==", "syntactic") - - sym_bool1 = Symbol(True) - sym_bool2 = Symbol(True) - sym_bool3 = Symbol(False) - - assert sym_bool1 == sym_bool2 - display_op(f"{sym_bool1} == {sym_bool2}", sym_bool1 == sym_bool2, "==", "syntactic") - assert not (sym_bool1 == sym_bool3) - display_op(f"{sym_bool1} == {sym_bool3}", sym_bool1 == sym_bool3, "==", "syntactic") - - sym_list1 = Symbol([1, 2, 3]) - sym_list2 = Symbol([1, 2, 3], semantic=True) # or can be converted to a semantic symbol with ".sym" method - sym_list3 = Symbol([3, 2, 1]) - - assert sym_list1 == sym_list2 - display_op(f"{sym_list1} == {sym_list2}", sym_list1 == sym_list2, "==", "syntactic") - assert not (sym_list1 == sym_list3) - display_op(f"{sym_list2} == {sym_list3}", sym_list2 == sym_list3, "==", "semantic") - -@pytest.mark.mandatory -def test_not_equals_op(): - """Test the OperatorPrimitives class methods.""" - - sym1_syn = Symbol('hello world') - sym2_syn = Symbol('hello world') - sym3_syn = Symbol('goodbye world') - - assert not (sym1_syn != sym2_syn) - display_op(f"'{sym1_syn}' != '{sym2_syn}'", sym1_syn != sym2_syn, "!=", "syntactic") - assert sym1_syn != sym3_syn - display_op(f"'{sym1_syn}' != '{sym3_syn}'", sym1_syn != sym3_syn, "!=", "syntactic") - - sym_greeting_sem = Symbol('Hello there!', semantic=True) # or can be converted to a semantic symbol with ".sym" method - sym_farewell_sem = Symbol('Goodbye friend!') - greeting_variant = 'Hi there!' - farewell_variant = 'See you later!' - - display_op(f"'{sym_greeting_sem}' != '{greeting_variant}'", sym_greeting_sem != greeting_variant, "!=", "semantic") - display_op(f"'{sym_farewell_sem}' != '{farewell_variant}'", sym_farewell_sem != farewell_variant, "!=", "semantic") - - sym_num1 = Symbol(42) - sym_num2 = Symbol(42) - sym_num3 = Symbol(24) - - assert not (sym_num1 != sym_num2) - display_op(f"{sym_num1} != {sym_num2}", sym_num1 != sym_num2, "!=", "syntactic") - assert sym_num1 != sym_num3 - display_op(f"{sym_num1} != {sym_num3}", sym_num1 != sym_num3, "!=", "syntactic") - - sym_bool1 = Symbol(True) - sym_bool2 = Symbol(True) - sym_bool3 = Symbol(False) - - assert not (sym_bool1 != sym_bool2) - display_op(f"{sym_bool1} != {sym_bool2}", sym_bool1 != sym_bool2, "!=", "syntactic") - assert sym_bool1 != sym_bool3 - display_op(f"{sym_bool1} != {sym_bool3}", sym_bool1 != sym_bool3, "!=", "syntactic") - - sym_list1 = Symbol([1, 2, 3]) - sym_list2 = Symbol([1, 2, 3], semantic=True) # or can be converted to a semantic symbol with ".sym" method - sym_list3 = Symbol([3, 2, 1]) - - assert not (sym_list1 != sym_list2) - display_op(f"{sym_list1} != {sym_list2}", sym_list1 != sym_list2, "!=", "syntactic") - assert sym_list1 != sym_list3 - display_op(f"{sym_list2} != {sym_list3}", sym_list2 != sym_list3, "!=", "semantic") - -@pytest.mark.mandatory -def test_comparison_op(): - """Test the OperatorPrimitives class methods.""" - - sym_num1 = Symbol(15) - sym_num2 = Symbol(8) - assert sym_num1 > sym_num2 - display_op(f"{sym_num1} > {sym_num2}", sym_num1 > sym_num2, ">", "syntactic") - - sym_float1 = Symbol(3.14) - sym_float2 = Symbol(2.71) - assert sym_float1 > sym_float2 - display_op(f"{sym_float1} > {sym_float2}", sym_float1 > sym_float2, ">", "syntactic") - - sym_large = Symbol('enormous', semantic=True) # or can be converted to a semantic symbol with ".sym" method - sym_small = Symbol('tiny') - display_op(f"'{sym_large}' > '{sym_small}'", sym_large > sym_small, ">", "semantic") - - sym_list1 = len(Symbol([5, 6])) - sym_list2 = len(Symbol([4, 5])) - display_op(f"{sym_list1} > {sym_list2}", sym_list1 > sym_list2, ">", "syntactic") - - sym_num3 = Symbol(12) - sym_num4 = Symbol(20) - assert sym_num3 < sym_num4 - display_op(f"{sym_num3} < {sym_num4}", sym_num3 < sym_num4, "<", "syntactic") - - sym_float3 = Symbol(1.5) - sym_float4 = Symbol(2.8) - assert sym_float3 < sym_float4 - display_op(f"{sym_float3} < {sym_float4}", sym_float3 < sym_float4, "<", "syntactic") - - sym_str3 = Symbol('cat', semantic=True) # or can be converted to a semantic symbol with ".sym" method - sym_str4 = Symbol('dog') - display_op(f"'{sym_str3}' < '{sym_str4}'", sym_str3 < sym_str4, "<", "semantic") - - sym_cold = Symbol('freezing', semantic=True) # or can be converted to a semantic symbol with ".sym" method - sym_hot = Symbol('scorching') - display_op(f"'{sym_cold}' < '{sym_hot}'", sym_cold < sym_hot, "<", "semantic") - - sym_list3 = len(Symbol([1, 2])) - sym_list4 = len(Symbol([1, 2, 3])) - display_op(f"{sym_list3} < {sym_list4}", sym_list3 < sym_list4, "<", "syntactic") - - sym_num5 = Symbol(25) - sym_num6 = Symbol(25) - assert sym_num5 >= sym_num6 - display_op(f"{sym_num5} >= {sym_num6}", sym_num5 >= sym_num6, ">=", "syntactic") - - sym_num7 = Symbol(30) - sym_num8 = Symbol(18) - assert sym_num7 >= sym_num8 - display_op(f"{sym_num7} >= {sym_num8}", sym_num7 >= sym_num8, ">=", "syntactic") - - sym_str5 = len(Symbol('python')) - sym_str6 = len(Symbol('python')) - assert sym_str5 >= sym_str6 - display_op(f"'{sym_str5}' >= '{sym_str6}'", sym_str5 >= sym_str6, ">=", "syntactic") - - sym_fast = Symbol('lightning speed', semantic=True) # or can be converted to a semantic symbol with ".sym" method - sym_slow = Symbol('snail pace') - display_op(f"'{sym_fast}' >= '{sym_slow}'", sym_fast >= sym_slow, ">=", "semantic") - - sym_num9 = Symbol(7) - sym_num10 = Symbol(10) - assert sym_num9 <= sym_num10 - display_op(f"{sym_num9} <= {sym_num10}", sym_num9 <= sym_num10, "<=", "syntactic") - - sym_num11 = Symbol(33) - sym_num12 = Symbol(33) - assert sym_num11 <= sym_num12 - display_op(f"{sym_num11} <= {sym_num12}", sym_num11 <= sym_num12, "<=", "syntactic") - - sym_weak = Symbol('fragile', semantic=True) # or can be converted to a semantic symbol with ".sym" method - sym_strong = Symbol('robust') - display_op(f"'{sym_weak}' <= '{sym_strong}'", sym_weak <= sym_strong, "<=", "semantic") - - sym_word_num = Symbol('fifty', semantic=True) # or can be converted to a semantic symbol with ".sym" method - regular_num = 45 - display_op(f"'{sym_word_num}' > {regular_num}", sym_word_num > regular_num, ">", "semantic") - -@pytest.mark.mandatory -def test_shift_op(): - """Test the OperatorPrimitives class methods.""" - - sym_int8 = Symbol(8) - sym_int2 = Symbol(2) - sym_int16 = Symbol(16) - - assert (sym_int8 << sym_int2) == 32 - display_op(f"{sym_int8} << {sym_int2}", sym_int8 << sym_int2, "<<", "syntactic") - assert (sym_int2 << sym_int8) == 512 - display_op(f"{sym_int2} << {sym_int8}", sym_int2 << sym_int8, "<<", "syntactic") - - assert (sym_int16 >> sym_int2) == 4 - display_op(f"{sym_int16} >> {sym_int2}", sym_int16 >> sym_int2, ">>", "syntactic") - assert (sym_int8 >> sym_int2) == 2 - display_op(f"{sym_int8} >> {sym_int2}", sym_int8 >> sym_int2, ">>", "syntactic") - - regular_int4 = 4 - assert (regular_int4 << sym_int2) == 16 - display_op(f"{regular_int4} << {sym_int2}", regular_int4 << sym_int2, "<<", "syntactic") - - regular_int32 = 32 - assert (regular_int32 >> sym_int2) == 8 - display_op(f"{regular_int32} >> {sym_int2}", regular_int32 >> sym_int2, ">>", "syntactic") - - sym_inplace_left = Symbol(5) - original_value = sym_inplace_left.value - sym_inplace_left <<= Symbol(3) - assert sym_inplace_left == 40 - display_op(f"{original_value} <<= 3", sym_inplace_left, "<<=", "syntactic") - - sym_inplace_right = Symbol(64) - original_value = sym_inplace_right.value - sym_inplace_right >>= Symbol(3) - assert sym_inplace_right == 8 - display_op(f"{original_value} >>= 3", sym_inplace_right, ">>=", "syntactic") - - sym_text = Symbol('data stream', semantic=True) - sym_direction = Symbol('left') - display_op(f"'{sym_text}' << '{sym_direction}'", sym_text << sym_direction, "<<", "semantic") - - sym_info = Symbol('information flow', semantic=True) - sym_right_dir = Symbol('right') - display_op(f"'{sym_info}' >> '{sym_right_dir}'", sym_info >> sym_right_dir, ">>", "semantic") - - sym_numeric_str = Symbol('8', semantic=True) - sym_shift_amount = Symbol('2') - display_op(f"'{sym_numeric_str}' << '{sym_shift_amount}'", sym_numeric_str << sym_shift_amount, "<<", "semantic") - display_op(f"'{sym_numeric_str}' >> '{sym_shift_amount}'", sym_numeric_str >> sym_shift_amount, ">>", "semantic") - - sym_base = Symbol(12) - regular_shift = 1 - assert (sym_base << regular_shift) == 24 - display_op(f"{sym_base} << {regular_shift}", sym_base << regular_shift, "<<", "syntactic") - assert (sym_base >> regular_shift) == 6 - display_op(f"{sym_base} >> {regular_shift}", sym_base >> regular_shift, ">>", "syntactic") - - sym_zero = Symbol(0) - sym_neg = Symbol(-4) - - assert (sym_zero << sym_int2) == 0 - display_op(f"{sym_zero} << {sym_int2}", sym_zero << sym_int2, "<<", "syntactic") - display_op(f"{sym_neg} << {sym_int2}", sym_neg << sym_int2, "<<", "syntactic") - display_op(f"{sym_neg} >> {sym_int2}", sym_neg >> sym_int2, ">>", "syntactic") - - sym_priority = Symbol('high priority task', semantic=True) - sym_urgency = Symbol('urgent') - display_op(f"'{sym_priority}' << '{sym_urgency}'", sym_priority << sym_urgency, "<<", "semantic") - - sym_process = Symbol('data processing', semantic=True) - sym_downstream = Symbol('downstream') - display_op(f"'{sym_process}' >> '{sym_downstream}'", sym_process >> sym_downstream, ">>", "semantic") - - sym_chain = Symbol(1) - chained_result = sym_chain << Symbol(2) << Symbol(1) - assert chained_result == 8 - display_op(f"1 << 2 << 1", chained_result, "<<", "syntactic") - -@pytest.mark.mandatory -def test_bitwise_logical_op(): - """Test the OperatorPrimitives class methods.""" - - sym_int12 = Symbol(12) - sym_int10 = Symbol(10) - - assert (sym_int12 & sym_int10) == 8 - display_op(f"{sym_int12} & {sym_int10}", sym_int12 & sym_int10, "&", "syntactic") - - sym_int5 = Symbol(5) - sym_int3 = Symbol(3) - - assert (sym_int5 | sym_int3) == 7 - display_op(f"{sym_int5} | {sym_int3}", sym_int5 | sym_int3, "|", "syntactic") - - sym_true = Symbol(True) - sym_false = Symbol(False) - - assert (sym_true & sym_false) == False - display_op(f"{sym_true} & {sym_false}", sym_true & sym_false, "&", "syntactic") - assert (sym_true | sym_false) == True - display_op(f"{sym_true} | {sym_false}", sym_true | sym_false, "|", "syntactic") - - sym_inplace_and = Symbol(15) - original_value = sym_inplace_and.value - sym_inplace_and &= Symbol(7) - assert sym_inplace_and == 7 - display_op(f"{original_value} &= 7", sym_inplace_and, "&=", "syntactic") - - sym_inplace_or = Symbol(4) - original_value = sym_inplace_or.value - sym_inplace_or |= Symbol(2) - assert sym_inplace_or == 6 - display_op(f"{original_value} |= 2", sym_inplace_or, "|=", "syntactic") - - horn_rule = Symbol('The horn only sounds on Sundays.', semantic=True) - observation = Symbol('I hear the horn.') - conclusion = horn_rule & observation - display_op(f"'{horn_rule}' & '{observation}'", conclusion, "&", "semantic") - - fact1 = Symbol('All cats are mammals.', semantic=True) - fact2 = Symbol('Fluffy is a cat.') - inference = fact1 & fact2 - display_op(f"'{fact1}' & '{fact2}'", inference, "&", "semantic") - - option1 = Symbol('It might rain today.', semantic=True) - option2 = Symbol('It could be sunny.') - possibilities = option1 | option2 - display_op(f"'{option1}' | '{option2}'", possibilities, "|", "semantic") - - condition = Symbol('If you study hard, you will pass.', semantic=True) - action = Symbol('John studies hard.') - result = condition & action - display_op(f"'{condition}' & '{action}'", result, "&", "semantic") - - evidence1 = Symbol('The suspect was seen at the scene.', semantic=True) - evidence2 = Symbol('His fingerprints were found.') - combined_evidence = evidence1 & evidence2 - display_op(f"'{evidence1}' & '{evidence2}'", combined_evidence, "&", "semantic") - - scenario1 = Symbol('The meeting could be postponed.', semantic=True) - scenario2 = Symbol('The meeting might be canceled.') - alternatives = scenario1 | scenario2 - display_op(f"'{scenario1}' | '{scenario2}'", alternatives, "|", "semantic") - - bool_condition = Symbol(True) - text_condition = Symbol('The weather is good.', semantic=True) - mixed_and = bool_condition & text_condition - display_op(f"{bool_condition} & '{text_condition}'", mixed_and, "&", "semantic") - - regular_int = 6 - sym_right = Symbol(3) - assert (regular_int & sym_right) == 2 - display_op(f"{regular_int} & {sym_right}", regular_int & sym_right, "&", "syntactic") - assert (regular_int | sym_right) == 7 - display_op(f"{regular_int} | {sym_right}", regular_int | sym_right, "|", "syntactic") - - premise1 = Symbol('All birds can fly.') - premise2 = Symbol('Penguins are birds.') - premise3 = Symbol('Penguins cannot fly.') - - contradiction = premise1.sem & premise2 & premise3 - display_op(f"'{premise1}' & '{premise2}' & '{premise3}'", contradiction, "&", "semantic") - - diagnosis1 = Symbol('The patient has flu.') - diagnosis2 = Symbol('The patient has cold.') - diagnosis3 = Symbol('The patient has allergies.') - - possible_diagnoses = diagnosis1.sem | diagnosis2 | diagnosis3 - display_op(f"'{diagnosis1}' | '{diagnosis2}' | '{diagnosis3}'", possible_diagnoses, "|", "semantic") - - sym_int9 = Symbol(9) - sym_int6 = Symbol(6) - - assert (sym_int9 ^ sym_int6) == 15 - display_op(f"{sym_int9} ^ {sym_int6}", sym_int9 ^ sym_int6, "^", "syntactic") - - sym_int12 = Symbol(12) - sym_int7 = Symbol(7) - - assert (sym_int12 ^ sym_int7) == 11 - display_op(f"{sym_int12} ^ {sym_int7}", sym_int12 ^ sym_int7, "^", "syntactic") - - assert (sym_true ^ sym_false) == True - display_op(f"{sym_true} ^ {sym_false}", sym_true ^ sym_false, "^", "syntactic") - assert (sym_true ^ sym_true) == False - display_op(f"{sym_true} ^ {sym_true}", sym_true ^ sym_true, "^", "syntactic") - - sym_inplace_xor = Symbol(10) - original_value = sym_inplace_xor.value - sym_inplace_xor ^= Symbol(3) - assert sym_inplace_xor == 9 - display_op(f"{original_value} ^= 3", sym_inplace_xor, "^=", "syntactic") - - exclusive1 = Symbol('Either it will rain today.', semantic=True) - exclusive2 = Symbol('Or it will be sunny.') - either_or = exclusive1 ^ exclusive2 - display_op(f"'{exclusive1}' ^ '{exclusive2}'", either_or, "^", "semantic") - - statement1 = Symbol('The door is open.', semantic=True) - statement2 = Symbol('The door is closed.') - contradiction_xor = statement1 ^ statement2 - display_op(f"'{statement1}' ^ '{statement2}'", contradiction_xor, "^", "semantic") - - choice1 = Symbol('Take the highway route.') - choice2 = Symbol('Take the scenic route.') - exclusive_choice = choice1.sem ^ choice2 - display_op(f"'{choice1}' ^ '{choice2}'", exclusive_choice, "^", "semantic") - - regular_int = 8 - sym_right_xor = Symbol(5) - assert (regular_int ^ sym_right_xor) == 13 - display_op(f"{regular_int} ^ {sym_right_xor}", regular_int ^ sym_right_xor, "^", "syntactic") - - hypothesis1 = Symbol('The problem is hardware related.') - hypothesis2 = Symbol('The problem is software related.') - exclusive_diagnosis = hypothesis1.sem ^ hypothesis2 - display_op(f"'{hypothesis1}' ^ '{hypothesis2}'", exclusive_diagnosis, "^", "semantic") - -@pytest.mark.mandatory -def test_arithmetic_op(): - """Test the OperatorPrimitives class methods.""" - - sym_int8 = Symbol(8) - sym_int5 = Symbol(5) - - assert (sym_int8 + sym_int5) == 13 - display_op(f"{sym_int8} + {sym_int5}", sym_int8 + sym_int5, "+", "syntactic") - assert (sym_int8 - sym_int5) == 3 - display_op(f"{sym_int8} - {sym_int5}", sym_int8 - sym_int5, "-", "syntactic") - - sym_inplace_add = Symbol(10) - original_value = sym_inplace_add.value - sym_inplace_add += Symbol(7) - assert sym_inplace_add == 17 - display_op(f"{original_value} += 7", sym_inplace_add, "+=", "syntactic") - - sym_inplace_sub = Symbol(15) - original_value = sym_inplace_sub.value - sym_inplace_sub -= Symbol(6) - assert sym_inplace_sub == 9 - display_op(f"{original_value} -= 6", sym_inplace_sub, "-=", "syntactic") - - regular_int = 12 - sym_right = Symbol(4) - assert (regular_int + sym_right) == 16 - display_op(f"{regular_int} + {sym_right}", regular_int + sym_right, "+", "syntactic") - assert (regular_int - sym_right) == 8 - display_op(f"{regular_int} - {sym_right}", regular_int - sym_right, "-", "syntactic") - - enemy_text = Symbol('Hello my enemy', semantic=True) - result1 = enemy_text - 'enemy' + 'friend' - display_op(f"'{enemy_text}' - 'enemy' + 'friend'", result1, "- +", "semantic") - - original_msg = Symbol('I dislike this situation') - result2 = original_msg.sem - 'dislike' + 'love' - display_op(f"'{original_msg}' - 'dislike' + 'love'", result2, "- +", "semantic") - - problem_text = Symbol('The old system is broken', semantic=True) - solution = problem_text - 'old' - 'broken' + 'new' + 'working' - display_op(f"'{problem_text}' - 'old' - 'broken' + 'new' + 'working'", solution, "- - + +", "semantic") - - negative_review = Symbol('This product is terrible and useless') - positive_review = negative_review.sem - 'terrible' - 'useless' + 'amazing' + 'helpful' - display_op(f"'{negative_review}' - 'terrible' - 'useless' + 'amazing' + 'helpful'", positive_review, "- - + +", "semantic") - - incomplete_task = Symbol('The project is half done', semantic=True) - complete_task = incomplete_task - 'half done' + 'completed' - display_op(f"'{incomplete_task}' - 'half done' + 'completed'", complete_task, "- +", "semantic") - - mood_text = Symbol('I am feeling sad today') - happy_mood = mood_text.sem - 'sad' + 'happy' - display_op(f"'{mood_text}' - 'sad' + 'happy'", happy_mood, "- +", "semantic") - - wrong_info = Symbol('The answer is definitely wrong', semantic=True) - correct_info = wrong_info - 'wrong' + 'correct' - display_op(f"'{wrong_info}' - 'wrong' + 'correct'", correct_info, "- +", "semantic") - - weak_statement = Symbol('This might be weak') - strong_statement = weak_statement.sem - 'weak' + 'strong' - display_op(f"'{weak_statement}' - 'weak' + 'strong'", strong_statement, "- +", "semantic") - -@pytest.mark.mandatory -def test_string_concatenation_op(): - """Test the OperatorPrimitives class methods.""" - - sym_str1 = Symbol('Hello') - sym_str2 = Symbol(' World') - - result = sym_str1 @ sym_str2 - assert result == 'Hello World' - display_op(f"'{sym_str1}' @ '{sym_str2}'", result, "@", "syntactic") - - sym_first = Symbol('Python') - sym_second = Symbol(' Programming') - sym_third = Symbol(' Language') - - chain_result = sym_first @ sym_second @ sym_third - assert chain_result == 'Python Programming Language' - display_op(f"'{sym_first}' @ '{sym_second}' @ '{sym_third}'", chain_result, "@", "syntactic") - - sym_inplace = Symbol('Start') - original_value = sym_inplace.value - sym_inplace @= Symbol(' End') - assert sym_inplace == 'Start End' - display_op(f"'{original_value}' @= ' End'", sym_inplace, "@=", "syntactic") - - regular_str = 'Tail' - sym_suffix = Symbol('Head ') - result_mixed = regular_str @ sym_suffix - assert result_mixed == 'Head Tail' - display_op(f"'{regular_str}' @ '{sym_suffix}'", result_mixed, "@", "syntactic") - - sym_base = Symbol('Base') - regular_suffix = ' Extension' - result_reverse = sym_base @ regular_suffix - assert result_reverse == 'Base Extension' - display_op(f"'{sym_base}' @ '{regular_suffix}'", result_reverse, "@", "syntactic") - - empty_sym = Symbol('') - text_sym = Symbol('Content') - result_empty = empty_sym @ text_sym - assert result_empty == 'Content' - display_op(f"'{empty_sym}' @ '{text_sym}'", result_empty, "@", "syntactic") - -@pytest.mark.mandatory -def test_division_power_modulo_multiply_op(): - """Test the OperatorPrimitives class methods.""" - - sym_int12 = Symbol(12) - sym_int3 = Symbol(3) - sym_int4 = Symbol(4) - - assert (sym_int12 / sym_int3) == 4.0 - display_op(f"{sym_int12} / {sym_int3}", sym_int12 / sym_int3, "/", "syntactic") - assert (sym_int12 // sym_int3) == 4 - display_op(f"{sym_int12} // {sym_int3}", sym_int12 // sym_int3, "//", "syntactic") - - sym_int2 = Symbol(2) - assert (sym_int4 ** sym_int2) == 16 - display_op(f"{sym_int4} ** {sym_int2}", sym_int4 ** sym_int2, "**", "syntactic") - - sym_int10 = Symbol(10) - assert (sym_int10 % sym_int3) == 1 - display_op(f"{sym_int10} % {sym_int3}", sym_int10 % sym_int3, "%", "syntactic") - - sym_int5 = Symbol(5) - assert (sym_int5 * sym_int4) == 20 - display_op(f"{sym_int5} * {sym_int4}", sym_int5 * sym_int4, "*", "syntactic") - - sym_inplace_div = Symbol(20.0) - original_value = sym_inplace_div.value - sym_inplace_div /= Symbol(4) - assert sym_inplace_div == 5.0 - display_op(f"{original_value} /= 4", sym_inplace_div, "/=", "syntactic") - - sym_inplace_floordiv = Symbol(17) - original_value = sym_inplace_floordiv.value - sym_inplace_floordiv //= Symbol(3) - assert sym_inplace_floordiv == 5 - display_op(f"{original_value} //= 3", sym_inplace_floordiv, "//=", "syntactic") - - sym_inplace_pow = Symbol(3) - original_value = sym_inplace_pow.value - sym_inplace_pow **= Symbol(3) - assert sym_inplace_pow == 27 - display_op(f"{original_value} **= 3", sym_inplace_pow, "**=", "syntactic") - - sym_inplace_mod = Symbol(13) - original_value = sym_inplace_mod.value - sym_inplace_mod %= Symbol(5) - assert sym_inplace_mod == 3 - display_op(f"{original_value} %= 5", sym_inplace_mod, "%=", "syntactic") - - sym_inplace_mul = Symbol(6) - original_value = sym_inplace_mul.value - sym_inplace_mul *= Symbol(7) - assert sym_inplace_mul == 42 - display_op(f"{original_value} *= 7", sym_inplace_mul, "*=", "syntactic") - - regular_int = 15 - sym_right = Symbol(3) - assert (regular_int / sym_right) == 5.0 - display_op(f"{regular_int} / {sym_right}", regular_int / sym_right, "/", "syntactic") - assert (regular_int * sym_right) == 45 - display_op(f"{regular_int} * {sym_right}", regular_int * sym_right, "*", "syntactic") - - sym_str = Symbol('apple,banana,cherry') - split_result = sym_str / ',' - expected = ['apple', 'banana', 'cherry'] - assert split_result.value == expected - display_op(f"'{sym_str}' / ','", split_result, "/", "syntactic") - - sym_text = Symbol('hello world hello') - split_by_space = sym_text / ' ' - expected_split = ['hello', 'world', 'hello'] - assert split_by_space.value == expected_split - display_op(f"'{sym_text}' / ' '", split_by_space, "/", "syntactic") - - sym_sentence = Symbol('one-two-three-four') - split_by_dash = sym_sentence / '-' - expected_dash = ['one', 'two', 'three', 'four'] - assert split_by_dash.value == expected_dash - display_op(f"'{sym_sentence}' / '-'", split_by_dash, "/", "syntactic") - -@pytest.mark.mandatory -def test_casting_pr(): - """Test the CastingPrimitives class methods.""" - - # Test cast() method with different types - sym_str_num = Symbol('42') - casted_int = sym_str_num.cast(int) - assert casted_int == 42 - assert isinstance(casted_int, int) - display_op(f"['{sym_str_num}'].cast(int)", casted_int, "cast", "syntactic") - - sym_int = Symbol(123) - casted_str = sym_int.cast(str) - assert casted_str == '123' - assert isinstance(casted_str, str) - display_op(f"[{sym_int}].cast(str)", casted_str, "cast", "syntactic") - - sym_str_float = Symbol('3.14') - casted_float = sym_str_float.cast(float) - assert casted_float == 3.14 - assert isinstance(casted_float, float) - display_op(f"['{sym_str_float}'].cast(float)", casted_float, "cast", "syntactic") - - sym_int_bool = Symbol(1) - casted_bool = sym_int_bool.cast(bool) - assert casted_bool is True - assert isinstance(casted_bool, bool) - display_op(f"[{sym_int_bool}].cast(bool)", casted_bool, "cast", "syntactic") - - # Test to() method (alias for cast) - sym_str_to_int = Symbol('99') - to_result = sym_str_to_int.to(int) - assert to_result == 99 - assert isinstance(to_result, int) - display_op(f"['{sym_str_to_int}'].to(int)", to_result, "to", "syntactic") - - # Test str() method - sym_various = Symbol(456) - str_result = sym_various.str() - assert str_result == '456' - assert isinstance(str_result, str) - display_op(f"[{sym_various}].str()", str_result, "str", "syntactic") - - sym_float_str = Symbol(2.718) - str_float_result = sym_float_str.str() - assert str_float_result == '2.718' - display_op(f"[{sym_float_str}].str()", str_float_result, "str", "syntactic") - - sym_bool_str = Symbol(True) - str_bool_result = sym_bool_str.str() - assert str_bool_result == 'True' - display_op(f"[{sym_bool_str}].str()", str_bool_result, "str", "syntactic") - - # Test int() method - sym_str_int = Symbol('789') - int_result = sym_str_int.int() - assert int_result == 789 - assert isinstance(int_result, int) - display_op(f"['{sym_str_int}'].int()", int_result, "int", "syntactic") - - sym_float_int = Symbol(9.7) - int_from_float = sym_float_int.int() - assert int_from_float == 9 - display_op(f"[{sym_float_int}].int()", int_from_float, "int", "syntactic") - - sym_bool_int = Symbol(True) - int_from_bool = sym_bool_int.int() - assert int_from_bool == 1 - display_op(f"[{sym_bool_int}].int()", int_from_bool, "int", "syntactic") - - # Test float() method - sym_str_float_test = Symbol('12.34') - float_result = sym_str_float_test.float() - assert float_result == 12.34 - assert isinstance(float_result, float) - display_op(f"['{sym_str_float_test}'].float()", float_result, "float", "syntactic") - - sym_int_float = Symbol(55) - float_from_int = sym_int_float.float() - assert float_from_int == 55.0 - display_op(f"[{sym_int_float}].float()", float_from_int, "float", "syntactic") - - # Test bool() method - sym_int_zero = Symbol(0) - bool_from_zero = sym_int_zero.bool() - assert bool_from_zero is False - display_op(f"[{sym_int_zero}].bool()", bool_from_zero, "bool", "syntactic") - - sym_int_nonzero = Symbol(42) - bool_from_nonzero = sym_int_nonzero.bool() - assert bool_from_nonzero is True - display_op(f"[{sym_int_nonzero}].bool()", bool_from_nonzero, "bool", "syntactic") - - sym_str_empty = Symbol('') - bool_from_empty = sym_str_empty.bool() - assert bool_from_empty is False - display_op(f"['{sym_str_empty}'].bool()", bool_from_empty, "bool", "syntactic") - - sym_str_nonempty = Symbol('hello') - bool_from_string = sym_str_nonempty.bool() - assert bool_from_string is True - display_op(f"['{sym_str_nonempty}'].bool()", bool_from_string, "bool", "syntactic") - - # Test ast() method with different literal types - sym_list_str = Symbol('[1, 2, 3]') - ast_list = sym_list_str.ast() - assert ast_list == [1, 2, 3] - assert isinstance(ast_list, list) - display_op(f"['{sym_list_str}'].ast()", ast_list, "ast", "syntactic") - - sym_dict_str = Symbol("{'a': 1, 'b': 2}") - ast_dict = sym_dict_str.ast() - assert ast_dict == {'a': 1, 'b': 2} - assert isinstance(ast_dict, dict) - display_op(f"['{sym_dict_str}'].ast()", ast_dict, "ast", "syntactic") - - sym_tuple_str = Symbol('(10, 20, 30)') - ast_tuple = sym_tuple_str.ast() - assert ast_tuple == (10, 20, 30) - assert isinstance(ast_tuple, tuple) - display_op(f"['{sym_tuple_str}'].ast()", ast_tuple, "ast", "syntactic") - - sym_none_str = Symbol('None') - ast_none = sym_none_str.ast() - assert ast_none is None - display_op(f"['{sym_none_str}'].ast()", ast_none, "ast", "syntactic") - -@pytest.mark.mandatory -def test_iteration_pr(): - """Test the IterationPrimitives class methods.""" - - # Test __getitem__ with lists - syntactic - sym_list_syn = Symbol([10, 20, 30, 40, 50]) - item_syn = sym_list_syn[1] - assert item_syn == 20 - display_op(f"{sym_list_syn}[1]", item_syn, "getitem", "syntactic") - - item_neg = sym_list_syn[-1] - assert item_neg == 50 - display_op(f"{sym_list_syn}[-1]", item_neg, "getitem", "syntactic") - - slice_result = sym_list_syn[1:3] - assert slice_result == [20, 30] - display_op(f"{sym_list_syn}[1:3]", slice_result, "getitem", "syntactic") - - # Test __getitem__ with lists - semantic - sym_list_sem = Symbol([10, 20, 30, 40, 50], semantic=True) - item_sem = sym_list_sem[2] - assert item_sem == 30 - display_op(f"{sym_list_sem}[2]", item_sem, "getitem", "semantic") - - # Test __getitem__ with dictionaries - syntactic - sym_dict_syn = Symbol({'a': 1, 'b': 2, 'c': 3}) - dict_item_syn = sym_dict_syn['b'] - assert dict_item_syn == 2 - display_op(f"{sym_dict_syn}['b']", dict_item_syn, "getitem", "syntactic") - - # Test __getitem__ with dictionaries - semantic - sym_dict_sem = Symbol({'name': 'Alice', 'age': 30, 'city': 'NYC'}, semantic=True) - dict_item_sem = sym_dict_sem['Return any names'] - assert dict_item_sem == 'Alice' - display_op(f"{sym_dict_sem}['Return any names']", dict_item_sem, "getitem", "semantic") - - sym_colors = Symbol({'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}, semantic=True) - color_key = 'primary color' - color_result = sym_colors[color_key] - display_op(f"{sym_colors}['{color_key}']", color_result, "getitem", "semantic") - - sym_animals = Symbol(['cat', 'dog', 'bird', 'fish']) - pet_query = 'domestic animal' - pet_result = sym_animals.sem[pet_query] - display_op(f"{sym_animals}['{pet_query}']", pet_result, "getitem", "semantic") - - # Test __getitem__ with tuples - sym_tuple_syn = Symbol((100, 200, 300)) - tuple_item = sym_tuple_syn[0] - assert tuple_item == 100 - display_op(f"{sym_tuple_syn}[0]", tuple_item, "getitem", "syntactic") - - # Test __getitem__ with numpy arrays - sym_array = Symbol(np.array([1, 2, 3, 4, 5])) - array_item = sym_array[3] - assert array_item == 4 - display_op(f"{sym_array}[3]", array_item, "getitem", "syntactic") - - # Test __setitem__ with lists - sym_list_modify = Symbol([1, 2, 3, 4, 5]) - original_list = sym_list_modify.value.copy() - sym_list_modify[2] = 99 - assert sym_list_modify.value[2] == 99 - display_op(f"{original_list}[2] = 99", sym_list_modify, "setitem", "syntactic") - - # Test __setitem__ with slice - sym_list_slice = Symbol([10, 20, 30, 40, 50]) - original_slice = sym_list_slice.value.copy() - sym_list_slice[1:3] = [888, 999] - assert sym_list_slice.value == [10, 888, 999, 40, 50] - display_op(f"{original_slice}[1:3] = [888, 999]", sym_list_slice, "setitem", "syntactic") - - # Test __setitem__ with dictionaries - sym_dict_modify = Symbol({'x': 10, 'y': 20}) - original_dict = sym_dict_modify.value.copy() - sym_dict_modify['z'] = 30 - assert sym_dict_modify.value['z'] == 30 - display_op(f"{original_dict}['z'] = 30", sym_dict_modify, "setitem", "syntactic") - - # Test __setitem__ with semantic mode - sym_dict_sem_modify = Symbol({'temperature': 20, 'humidity': 60, 'pressure': 1013}, semantic=True) - original_sem_dict = sym_dict_sem_modify.value.copy() - sym_dict_sem_modify['Change the temperature'] = 25 # Should semantically map to 'temperature' - display_op(f"{original_sem_dict}['Change the temperature'] = 25", sym_dict_sem_modify, "setitem", "semantic") - - # Test __delitem__ with dictionaries - sym_dict_delete = Symbol({'a': 1, 'b': 2, 'c': 3, 'd': 4}) - original_delete = sym_dict_delete.value.copy() - del sym_dict_delete['b'] - assert 'b' not in sym_dict_delete.value - assert sym_dict_delete.value == {'a': 1, 'c': 3, 'd': 4} - display_op(f"del {original_delete}['b']", sym_dict_delete, "delitem", "syntactic") - - # Test __delitem__ with semantic mode - sym_dict_sem_delete = Symbol({'first_name': 'John', 'last_name': 'Doe', 'age': 30}, semantic=True) - original_sem_delete = sym_dict_sem_delete.value.copy() - del sym_dict_sem_delete['surname'] # Should semantically map to 'last_name' - display_op(f"del {original_sem_delete}['surname']", sym_dict_sem_delete, "delitem", "semantic") - - # Test semantic dictionary key matching - sym_person = Symbol({'full_name': 'Alice Smith', 'birth_year': 1990, 'occupation': 'Engineer'}, semantic=True) - name_variants = ['identity', 'profession'] - for variant in name_variants: - result = sym_person[variant] - display_op(f"{sym_person}['{variant}']", result, "getitem", "semantic") - - # Test with mixed data types - sym_mixed = Symbol({'numbers': [1, 2, 3], 'text': 'hello'}) - nested_access = sym_mixed['numbers'] - assert nested_access == [1, 2, 3] - display_op(f"{sym_mixed}['numbers']", nested_access, "getitem", "syntactic") - -@pytest.mark.mandatory -def test_string_helper_pr(): - """Test the StringHelperPrimitives class methods.""" - - # Test split() method - sym_sentence = Symbol('hello world python programming') - split_result = sym_sentence.split(' ') - - expected_values = ['hello', 'world', 'python', 'programming'] - assert len(split_result) == len(expected_values) - for i, text in enumerate(split_result): - assert text == expected_values[i] - display_op(f"[{sym_sentence}].split(' ')", [s for s in split_result], "split", "syntactic") - - sym_csv = Symbol('apple,banana,cherry') - csv_split = sym_csv.split(',') - expected_values = ['apple', 'banana', 'cherry'] - assert len(csv_split) == len(expected_values) - for i, text in enumerate(csv_split): - assert text == expected_values[i] - display_op(f"[{sym_csv}].split(',')", [s for s in csv_split], "split", "syntactic") - - # Test split with different delimiters - sym_path = Symbol('home/user/documents/file.txt') - path_split = sym_path.split('/') - expected_values = ['home', 'user', 'documents', 'file.txt'] - assert len(path_split) == len(expected_values) - for i, text in enumerate(path_split): - assert text == expected_values[i] - display_op(f"[{sym_path}].split('/')", [s for s in path_split], "split", "syntactic") - - # Test join() method with list input - sym_words = Symbol(['Hello', 'beautiful', 'world']) - joined_space = sym_words.join(' ') - assert joined_space == 'Hello beautiful world' - display_op(f"[{sym_words}].join(' ')", joined_space, "join", "syntactic") - - joined_dash = sym_words.join('-') - assert joined_dash == 'Hello-beautiful-world' - display_op(f"[{sym_words}].join('-')", joined_dash, "join", "syntactic") - - # Test join with default delimiter (space) - joined_default = sym_words.join() - assert joined_default == 'Hello beautiful world' - display_op(f"[{sym_words}].join()", joined_default, "join", "syntactic") - - # Test startswith() method - sym_greeting = Symbol('Hello everyone!') - starts_hello = sym_greeting.startswith('Hello') - assert starts_hello is True - display_op(f"[{sym_greeting}].startswith('Hello')", starts_hello, "startswith", "syntactic") - - starts_bye = sym_greeting.startswith('Goodbye') - assert starts_bye is False - display_op(f"[{sym_greeting}].startswith('Goodbye')", starts_bye, "startswith", "syntactic") - - # Test with empty string - starts_empty = sym_greeting.startswith('') - assert starts_empty is True - display_op(f"[{sym_greeting}].startswith('')", starts_empty, "startswith", "syntactic") - - # Test endswith() method - sym_filename = Symbol('document.pdf') - ends_pdf = sym_filename.endswith('.pdf') - assert ends_pdf is True - display_op(f"[{sym_filename}].endswith('.pdf')", ends_pdf, "endswith", "syntactic") - - ends_txt = sym_filename.endswith('.txt') - assert ends_txt is False - display_op(f"[{sym_filename}].endswith('.txt')", ends_txt, "endswith", "syntactic") - - # Test with multiple possible endings - sym_code_file = Symbol('main.py') - ends_py = sym_code_file.endswith('.py') - assert ends_py is True - display_op(f"[{sym_code_file}].endswith('.py')", ends_py, "endswith", "syntactic") - - # Test with longer suffix - sym_backup = Symbol('data_backup_2024.tar.gz') - ends_tar_gz = sym_backup.endswith('.tar.gz') - assert ends_tar_gz is True - display_op(f"[{sym_backup}].endswith('.tar.gz')", ends_tar_gz, "endswith", "syntactic") - - # Test case sensitivity - sym_mixed_case = Symbol('FileNAME.TXT') - ends_lower = sym_mixed_case.endswith('.txt') - assert ends_lower is False - display_op(f"[{sym_mixed_case}].endswith('.txt')", ends_lower, "endswith", "syntactic") - - ends_upper = sym_mixed_case.endswith('.TXT') - assert ends_upper is True - display_op(f"[{sym_mixed_case}].endswith('.TXT')", ends_upper, "endswith", "syntactic") - - # Test edge cases - sym_empty = Symbol('') - empty_split = sym_empty.split(' ') - assert len(empty_split) == 1 and empty_split[0] == '' - display_op(f"[{sym_empty}].split(' ')", [s for s in empty_split], "split", "syntactic") - - sym_single_char = Symbol('a') - single_starts = sym_single_char.startswith('a') - assert single_starts is True - display_op(f"[{sym_single_char}].startswith('a')", single_starts, "startswith", "syntactic") - - single_ends = sym_single_char.endswith('a') - assert single_ends is True - display_op(f"[{sym_single_char}].endswith('a')", single_ends, "endswith", "syntactic") - - # Test semantic startswith() operations - sym_semantic_sentence = Symbol('The apple fell from the tree.', semantic=True) - starts_with_fruit = sym_semantic_sentence.startswith('fruit') - display_op(f"[{sym_semantic_sentence}].startswith('fruit')", starts_with_fruit, "startswith", "semantic") - - sym_dog_sentence = Symbol('My dog loves to play fetch.', semantic=True) - starts_with_animal = sym_dog_sentence.startswith('animal') - display_op(f"[{sym_dog_sentence}].startswith('animal')", starts_with_animal, "startswith", "semantic") - - # Test semantic endswith() operations - sym_success_sentence = Symbol('She studied hard and graduated with honors.', semantic=True) - ends_with_success = sym_success_sentence.endswith('success') - display_op(f"[{sym_success_sentence}].endswith('success')", ends_with_success, "endswith", "semantic") - - sym_cooking_sentence = Symbol('The chef prepared a delicious meal.', semantic=True) - starts_with_cooking = sym_cooking_sentence.startswith('cooking') - display_op(f"[{sym_cooking_sentence}].startswith('cooking')", starts_with_cooking, "startswith", "semantic") - - # Test negative semantic cases - sym_book_sentence = Symbol('The book was very interesting.', semantic=True) - starts_with_vehicle = sym_book_sentence.startswith('vehicle') - assert starts_with_vehicle is False - display_op(f"[{sym_book_sentence}].startswith('vehicle')", starts_with_vehicle, "startswith", "semantic") - - sym_peaceful_sentence = Symbol('The cat slept peacefully.', semantic=True) - ends_with_violence = sym_peaceful_sentence.endswith('violence') - assert ends_with_violence is False - display_op(f"[{sym_peaceful_sentence}].endswith('violence')", ends_with_violence, "endswith", "semantic") - - # Compare syntactic vs semantic behavior - sym_apple_syntactic = Symbol('The apple fell from the tree.') - sym_apple_semantic = Symbol('The apple fell from the tree.', semantic=True) - - syntactic_result = sym_apple_syntactic.startswith('fruit') - semantic_result = sym_apple_semantic.startswith('fruit') - - assert syntactic_result is False - display_op(f"[{sym_apple_syntactic}].startswith('fruit')", syntactic_result, "startswith", "syntactic") - display_op(f"[{sym_apple_semantic}].startswith('fruit')", semantic_result, "startswith", "semantic") - -@pytest.mark.mandatory -def test_comparison_pr(): - """Test the ComparisonPrimitives class methods.""" - - # Test equals() method - contextual comparison beyond simple equality - sym_greeting1 = Symbol('Hello, good morning!') - - # Test contextual equals with default context - result_default = sym_greeting1.equals('Hi there, good day!') - display_op(f"[{sym_greeting1}].equals('Hi there, good day!')", result_default, "equals", "semantic") - - # Test contextual equals with specific context - result_greeting = sym_greeting1.equals('Hi there, good day!', context='greeting context') - display_op(f"[{sym_greeting1}].equals('Hi there, good day!', context='greeting')", result_greeting, "equals", "semantic") - - # Test equals with different contexts - sym_formal = Symbol('Good morning, sir.') - sym_casual = Symbol('Hey, what is up?') - - formal_vs_casual = sym_formal.equals('Hey, what\'s up?', context='politeness level') - display_op(f"[{sym_formal}].equals('Hey, what\\'s up?', context='politeness')", formal_vs_casual, "equals", "semantic") - - sym_text = Symbol('The quick brown fox jumps over the lazy dog') - contains_fox = sym_text.contains('fox') - display_op(f"[{sym_text}].contains('fox')", contains_fox, "contains", "semantic") - - # Test contains with non-existent element - contains_cat = sym_text.contains('cat') - display_op(f"[{sym_text}].contains('cat')", contains_cat, "contains", "semantic") - - sym_semantic_text = Symbol('The vehicle moved quickly down the road') - contains_car = sym_semantic_text.contains('car') - display_op(f"[{sym_semantic_text}].contains('car')", contains_car, "contains", "semantic") - - # Test contains with list - sym_fruits = Symbol(['apple', 'banana', 'orange']) - contains_apple = sym_fruits.contains('apple') - display_op(f"[{sym_fruits}].contains('apple')", contains_apple, "contains", "semantic") - - contains_grape = sym_fruits.contains('grape') - assert contains_grape is False - display_op(f"[{sym_fruits}].contains('grape')", contains_grape, "contains", "semantic") - - sym_number = Symbol(42) - # Test with basic types - is_number = sym_number.isinstanceof('number') - display_op(f"[{sym_number}].isinstanceof('number')", is_number, "isinstanceof", "semantic") - - is_string = sym_number.isinstanceof('string') - display_op(f"[{sym_number}].isinstanceof('string')", is_string, "isinstanceof", "semantic") - - # Test with list symbol - sym_list = Symbol(['apple', 'banana', 'cherry']) - is_list = sym_list.isinstanceof('list') - display_op(f"[{sym_list}].isinstanceof('list')", is_list, "isinstanceof", "semantic") - - # Test with boolean symbol - sym_bool = Symbol(True) - is_logical = sym_bool.isinstanceof('logical value') - display_op(f"[{sym_bool}].isinstanceof('logical value')", is_logical, "isinstanceof", "semantic") - - # Test with more complex type queries - sym_complex = Symbol({'name': 'John', 'age': 30}) - is_person = sym_complex.isinstanceof('person data') - display_op(f"[{sym_complex}].isinstanceof('person data')", is_person, "isinstanceof", "semantic") - - sym_person = Symbol({'name': 'Alice', 'age': 25, 'city': 'Wonderland'}) - is_person = sym_person.isinstanceof('person') - display_op(f"[{sym_person}].isinstanceof('person')", is_person, "isinstanceof", "semantic") - - # Test edge cases for equals - sym_empty = Symbol('') - empty_equals = sym_empty.equals('', context='exact match') - display_op(f"[{sym_empty}].equals('', context='exact')", empty_equals, "equals", "semantic") - - # Test edge cases for contains - empty_contains = sym_empty.contains('') - display_op(f"[{sym_empty}].contains('')", empty_contains, "contains", "semantic") - - # Test comparison with different data types - sym_mixed = Symbol([1, 'two', 3.0, True]) - contains_string = sym_mixed.contains('two') - display_op(f"[{sym_mixed}].contains('two')", contains_string, "contains", "semantic") - - contains_bool = sym_mixed.contains(True) - display_op(f"[{sym_mixed}].contains(True)", contains_bool, "contains", "semantic") - - sym_semantic = Symbol('The dog is running in the park') - semantic_contains = sym_semantic.contains('animal') - display_op(f"[{sym_semantic}].contains('animal')", semantic_contains, "contains", "semantic") - -@pytest.mark.mandatory -def test_interpret_pr(): - """Test the ExpressionHandlingPrimitives class methods.""" - - # Test basic interpretation - sym_basic = Symbol('What is the tallest mountain in the world?') - result_basic = sym_basic.interpret() - display_op(f"[{sym_basic}].interpret()", result_basic, "interpret", "semantic") - - # Test symbolic expression interpretation - sym_analogy = Symbol('gravity : Earth :: radiation : ?') - result_analogy = sym_analogy.interpret() - display_op(f"[{sym_analogy}].interpret()", result_analogy, "interpret", "semantic") - - # Test mathematical expression interpretation - sym_math = Symbol("∫(3x² + 2x - 5)dx") - result_math = sym_math.interpret() - display_op(f"[{sym_math}].interpret()", result_math, "interpret", "semantic") - - # Test accumulation feature - sym_accumulate = Symbol('Relativistic electron formula') - result1 = sym_accumulate.interpret(accumulate=True) - display_op(f"[{sym_accumulate}].interpret(accumulate=True)", result1, "interpret", "semantic") - - result2 = result1.interpret('Assume the momentum to be extremely large', accumulate=True) - display_op(f"[{result1}].interpret('Assume the momentum to be extremely large', accumulate=True)", - result2, "interpret", "semantic") - - result3 = result2.interpret('Expand the formula to account for both mass and momentum', accumulate=True) - display_op(f"[{result2}].interpret('Expand the formula to account for both mass and momentum', accumulate=True)", - result3, "interpret", "semantic") - - # Check accumulated results - accumulated = sym_accumulate.get_results() - display_op(f"[{sym_accumulate}].get_results()", accumulated, "get_results", "syntactic") - assert len(accumulated) == 3, "Should have 3 accumulated results" - - # Test clear results - sym_accumulate.clear_results() - cleared = sym_accumulate.get_results() - display_op(f"[{sym_accumulate}].clear_results() then get_results()", cleared, "clear_results", "syntactic") - assert len(cleared) == 0, "Should have no results after clearing" - - # Test logical reasoning with constraints - sym_reasoning = Symbol('If every event has a cause, and the universe began with an event, what philosophical question arises?') - result_reasoning = sym_reasoning.interpret() - display_op(f"[{sym_reasoning}].interpret()", result_reasoning, "interpret", "semantic") - - # Test conditional interpretation - sym_conditional = Symbol("If x < 0 then 'negative' else if x == 0 then 'zero' else 'positive'") - results = [] - for val in [-5, 0, 10]: - result = sym_conditional.interpret(f"x = {val}") - results.append(result) - display_op(f"[{sym_conditional}].interpret('x = {val}')", result, "interpret", "semantic") - assert len(set([str(r) for r in results])) == 3, "Should get three different results for different inputs" - - # Test system with constraints - sym_constraint = Symbol("Find values for x and y where: x + y = 10, x - y = 4") - result_constraint = sym_constraint.interpret() - display_op(f"[{sym_constraint}].interpret()", result_constraint, "interpret", "semantic") - - # Test result type preservation - assert isinstance(result_basic, Symbol), "interpret should return a Symbol" - assert isinstance(result_analogy, Symbol), "interpret should return a Symbol" - assert hasattr(result_analogy, '_input'), "result should have _input attribute" - - # Test multiple interpretations maintain input reference - result_multi1 = sym_analogy.interpret() - result_multi2 = sym_analogy.interpret() - assert result_multi1._input == result_multi2._input, "Both results should reference same input" - -@pytest.mark.mandatory -def test_data_handling_pr(): - """Test the DataHandlingPrimitives class methods.""" - - # Test map() method with list containing fruits and animals - sym_mixed_list = Symbol(['apple', 'banana', 'cherry', 'cat', 'dog']) - mapped_result = sym_mixed_list.map('convert all fruits to vegetables') - display_op(f"[{sym_mixed_list}].map('convert all fruits to vegetables')", mapped_result, "map", "semantic") - - # Test map() with complex objects list - sym_complex_list = Symbol([ - {'name': 'John', 'type': 'person'}, - {'name': 'Fluffy', 'type': 'cat'}, - {'name': 'Jane', 'type': 'person'}, - {'name': 'Rex', 'type': 'dog'} - ]) - complex_mapped = sym_complex_list.map('change all animals to birds') - display_op(f"[{sym_complex_list}].map('change all animals to birds')", complex_mapped, "map", "semantic") - - # Test map() with numbers - sym_numbers = Symbol([1, 5, 10, 15, 20]) - number_mapped = sym_numbers.map('multiply small numbers (under 10) by 2') - display_op(f"[{sym_numbers}].map('multiply small numbers (under 10) by 2')", number_mapped, "map", "semantic") - - # Test map() with string - sym_string = Symbol("hello world") - string_mapped = sym_string.map('convert vowels to numbers: a=1, e=2, i=3, o=4, u=5') - display_op(f"[{sym_string}].map('convert vowels to numbers')", string_mapped, "map", "semantic") - - # Test map() with string consonants - sym_string2 = Symbol("PROGRAMMING") - string_mapped2 = sym_string2.map('make consonants lowercase, keep vowels uppercase') - display_op(f"[{sym_string2}].map('make consonants lowercase, keep vowels uppercase')", string_mapped2, "map", "semantic") - - # Test map() with dictionary - sym_dict = Symbol({'fruit1': 'apple', 'fruit2': 'banana', 'animal1': 'cat'}) - dict_mapped = sym_dict.map('convert all fruits to vegetables') - display_op(f"[{sym_dict}].map('convert all fruits to vegetables')", dict_mapped, "map", "semantic") - - # Test map() with tuple - sym_tuple = Symbol(('red', 'blue', 'green', 'yellow')) - tuple_mapped = sym_tuple.map('change primary colors to secondary colors') - display_op(f"[{sym_tuple}].map('change primary colors to secondary colors')", tuple_mapped, "map", "semantic") - - # Test map() with set - sym_set = Symbol({'happy', 'sad', 'angry', 'excited'}) - set_mapped = sym_set.map('convert emotions to weather conditions') - display_op(f"[{sym_set}].map('convert emotions to weather conditions')", set_mapped, "map", "semantic") - - # Test map() with dictionary - sym_dict = Symbol({'fruit1': 'apple', 'fruit2': 'banana', 'animal1': 'cat'}) - dict_mapped = sym_dict.map('convert all fruits to vegetables') - display_op(f"[{sym_dict}].map('convert all fruits to vegetables')", dict_mapped, "map", "semantic") - - # Test map() with complex dictionary - sym_complex_dict = Symbol({ - 'person1': {'name': 'John', 'type': 'human'}, - 'pet1': {'name': 'Fluffy', 'type': 'cat'}, - 'person2': {'name': 'Jane', 'type': 'human'} - }) - complex_dict_mapped = sym_complex_dict.map('change all animals to birds') - display_op(f"[{sym_complex_dict}].map('change all animals to birds')", complex_dict_mapped, "map", "semantic") - - # Test map() with tuple - sym_tuple = Symbol(('red', 'blue', 'green', 'yellow')) - tuple_mapped = sym_tuple.map('change primary colors to secondary colors') - display_op(f"[{sym_tuple}].map('change primary colors to secondary colors')", tuple_mapped, "map", "semantic") - - # Test map() with set - sym_set = Symbol({'happy', 'sad', 'angry', 'excited'}) - set_mapped = sym_set.map('convert emotions to weather conditions') - display_op(f"[{sym_set}].map('convert emotions to weather conditions')", set_mapped, "map", "semantic") - - # Test map() error handling with non-iterable - sym_int = Symbol(42) - try: - sym_int.map('some instruction') - except AssertionError as e: - display_op(f"[{sym_int}].map('some instruction')", f"AssertionError: {str(e)}", "map", "syntactic") - assert "Map can only be applied to iterable objects" in str(e) - else: - assert False, "map() should raise AssertionError for non-iterable input" - - # Test map() error handling without instruction - sym_list_no_instruction = Symbol([1, 2, 3]) - try: - sym_list_no_instruction.map() - except TypeError as e: - display_op(f"[{sym_list_no_instruction}].map()", f"TypeError: {str(e)}", "map", "syntactic") - else: - assert False, "map() should require an instruction parameter" - - # # Test clean method - # sym_dirty = Symbol("This text has multiple spaces and\n\nextra newlines.\t\tAnd tabs.") - # cleaned = sym_dirty.clean() - # display_op(f"[{sym_dirty}].clean()", cleaned, "clean", "semantic") - - # # Test summarize method - # sym_long = Symbol("""Python is a high-level, interpreted programming language known for its readability and simplicity. - # It was first released in 1991 by Guido van Rossum. Python supports multiple programming paradigms, - # including procedural, object-oriented, and functional programming. It has a comprehensive standard - # library and a large ecosystem of third-party packages that make it suitable for various applications, - # from web development to data science and machine learning. Python's philosophy emphasizes code - # readability with its notable use of significant whitespace.""") - # summarized = sym_long.summarize() - # assert len(str(summarized)) < len(str(sym_long)) - # display_op(f"[{sym_long}].summarize()", summarized, "summarize", "semantic") - - # # Test summarize with context - # context_summarized = sym_long.summarize(context="Focus on Python's use in data science") - # assert len(str(context_summarized)) < len(str(sym_long)) - # display_op(f"[{sym_long}].summarize(context='Focus on Python's use in data science')", - # context_summarized, "summarize", "semantic") - - # # Test outline method - # sym_complex = Symbol(dedent(""" - # #Introduction to Machine Learning - # Machine learning is a subset of artificial intelligence that focuses on building systems that learn from data. - # ## Supervised Learning - # Supervised learning involves training a model on labeled data. - # ### Classification - # Classification tasks involve predicting discrete categories. - # ### Regression - # Regression tasks involve predicting continuous values. - # ## Unsupervised Learning - # Unsupervised learning works with unlabeled data to find patterns.""")) - # outlined = sym_complex.outline() - # display_op(f"[{sym_complex}].outline()", outlined, "outline", "semantic") - - # # Test filter method (excluding) - # sym_mixed = Symbol("Dogs are loyal pets. Cats are independent pets. Hamsters are small pets.") - # filtered_ex = sym_mixed.filter(criteria="Cats") - # display_op(f"[{sym_mixed}].filter('Cats')", filtered_ex, "filter", "semantic") - - # # Test filter method (including) - # filtered_in = sym_mixed.filter(criteria="Dogs", include=True) - # display_op(f"[{sym_mixed}].filter('Dogs', include=True)", filtered_in, "filter", "semantic") - - # # Test modify method - # sym_original = Symbol("The quick brown fox jumps over the lazy dog.") - # changes = "Change 'quick' to 'fast' and 'lazy' to 'sleeping'" - # modified = sym_original.modify(changes=changes) - # display_op(f"[{sym_original}].modify('{changes}')", modified, "modify", "semantic") - - # # Test replace method - # sym_replace = Symbol("Python is a programming language. Python is easy to learn.") - # replaced = sym_replace.replace("Python", "JavaScript") - # display_op(f"[{sym_replace}].replace('Python', 'JavaScript')", replaced, "replace", "semantic") - - # # Test remove method - # sym_extra = Symbol("This text contains [unnecessary information] that should be removed.") - # removed = sym_extra.remove("[unnecessary information] ") - # display_op(f"[{sym_extra}].remove('[unnecessary information] ')", removed, "remove", "semantic") - - # # Test include method - # sym_base = Symbol("This is the main content.") - # included = sym_base.include("This is additional information.") - # display_op(f"[{sym_base}].include('This is additional information.')", included, "include", "semantic") - - # # Test combine method - # sym_first = Symbol("First part of the content.") - # combined = sym_first.combine("Second part of the content.") - # display_op(f"[{sym_first}].combine('Second part of the content.')", combined, "combine", "semantic") - -@pytest.mark.mandatory -def test_uniqueness_pr(): - """Test the UniquenessPrimitives class methods.""" - - # Test unique method with no keys - sym_repeated = Symbol("This is a test. This is another test. This is a third test.") - unique_result = sym_repeated.unique() - display_op(f"[\n{sym_repeated}\n].unique()", f"\n{unique_result}\n", "unique", "semantic") - - # Test unique method with specific keys - sym_structured = Symbol(dedent(""" - name: John, age: 30, city: New York - name: Jane, age: 30, city: New York - name: John, age: 25, city: Boston - """)) - unique_keys = sym_structured.unique(keys=['name', 'city']) - display_op(f"[\n{sym_structured}\n].unique(['name', 'city'])", f"\n{unique_keys}\n", "unique", "semantic") - - # Test compose method with simple text - sym_elements = Symbol("The sun rises in the east and sets in the west.") - composed = sym_elements.compose() - display_op(f"[\n{sym_elements}\n].compose()", f"\n{composed}\n", "compose", "semantic") - - # Test compose method with structured text - sym_story_elements = Symbol(dedent(""" - Character: Detective Smith - Setting: Dark alley in London - Time: Midnight - Weather: Heavy rain - """)) - story_composed = sym_story_elements.compose() - display_op(f"[\n{sym_story_elements}\n].compose()", f"\n{story_composed}\n", "compose", "semantic") - -@pytest.mark.mandatory -def test_pattern_matching_pr(): - """Test the PatternMatchingPrimitives class methods.""" - - # Test rank method with default parameters - sym_numbers = Symbol(dedent(""" - 5. Learn Python basics - 1. Install Python - 3. Practice coding - 2. Set up IDE - 4. Join community - """)) - ranked = sym_numbers.rank(measure='difficulty', order='desc') - display_op(f"[\n{sym_numbers}\n].rank('difficulty', 'desc')", f"\n{ranked}\n", "rank", "semantic") - - # Test rank with different measure and order - sym_tasks = Symbol(dedent(""" - Important task: Complete project proposal - Urgent task: Fix critical bug - Optional task: Update documentation - Critical task: Deploy hotfix - """)) - ranked_priority = sym_tasks.rank(measure='priority', order='asc') - display_op(f"[\n{sym_tasks}\n].rank('priority', 'asc')", f"\n{ranked_priority}\n", "rank", "semantic") - - # Test extract method with pattern - sym_contact = Symbol(dedent(""" - Contact Information: - Email: john.doe@email.com - Phone: +1-555-0123 - Address: 123 Main St, City - """)) - extracted = sym_contact.extract("contact details") - display_op(f"[\n{sym_contact}\n].extract('contact details')", f"\n{extracted}\n", "extract", "semantic") - - # Test extract with specific pattern - sym_text = Symbol(dedent(""" - Project deadline: 2024-03-15 - Budget allocated: $50,000 - Team size: 8 people - Status: In Progress - """)) - extracted_dates = sym_text.extract("dates and deadlines") - display_op(f"[\n{sym_text}\n].extract('dates and deadlines')", f"\n{extracted_dates}\n", "extract", "semantic") - - # Test correct method with syntax error - sym_code = Symbol(dedent(""" - def calculate_sum(a b): - return a + b - """)) - try: - exec(str(sym_code)) - except Exception as e: - corrected = sym_code.correct("Fix the code", exception=e) - display_op(f"[\n{sym_code}\n].correct('Fix the code', {type(e).__name__})", f"\n{corrected}\n", "correct", "semantic") - - # Test correct with type error - sym_type_error = Symbol(dedent(""" - def process_data(items): - return items.sort() - result = process_data([3, 1, 2]) - print(result + 1) # TypeError: NoneType + int - """)) - try: - exec(str(sym_type_error)) - except Exception as e: - corrected_type = sym_type_error.correct("Fix the code", exception=e) - display_op(f"[\n{sym_type_error}\n].correct('Fix the code', {type(e).__name__})", f"\n{corrected_type}\n", "correct", "semantic") - - # Test translate method - sym_english = Symbol("Hello, how are you today?") - translated = sym_english.translate("Spanish") - display_op(f"[{sym_english}].translate('Spanish')", translated, "translate", "semantic") - - # Test choice method - sym_weather = Symbol("Temperature: 85°F, Humidity: 70%, Conditions: Sunny") - cases = ["hot and humid", "mild", "cold and dry"] - weather_choice = sym_weather.choice(cases=cases, default="mild") - display_op(f"[{sym_weather}].choice({cases}, default='mild')", weather_choice, "choice", "semantic") - - # Test choice with more complex cases - sym_sentiment = Symbol("This product exceeded all my expectations! Absolutely wonderful!") - sentiment_cases = ["positive", "neutral", "negative"] - sentiment_choice = sym_sentiment.choice(cases=sentiment_cases, default="neutral") - display_op(f"[{sym_sentiment}].choice({sentiment_cases}, default='neutral')", sentiment_choice, "choice", "semantic") - -@pytest.mark.mandatory -def test_query_handling_pr(): - """Test the QueryHandlingPrimitives class methods.""" - - # Test query method with basic context - sym_data = Symbol(dedent(""" - Product: Laptop Computer - Price: $1299.99 - Brand: TechCorp - RAM: 16GB - Storage: 512GB SSD - Screen: 15.6 inch - """)) - - basic_query = sym_data.query("What is the price?") - display_op(f"[\n{sym_data}\n].query('What is the price?')", basic_query, "query", "semantic") - - # Test query with more specific context - tech_query = sym_data.query("specifications", prompt="List the technical specifications") - display_op(f"[\n{sym_data}\n].query('specifications', prompt='List the technical specifications')", tech_query, "query", "semantic") - - # Test query with complex data - sym_report = Symbol(dedent(""" - Quarterly Sales Report: - Q1: $2.5M (Growth: +15%) - Q2: $3.1M (Growth: +24%) - Q3: $2.8M (Growth: -10%) - Q4: $3.7M (Growth: +32%) - - Top Products: - 1. Software Licenses: $8.2M - 2. Hardware Sales: $3.9M - 3. Consulting Services: $1.9M - """)) - - performance_query = sym_report.query("growth trends", prompt="Analyze the quarterly growth patterns") - display_op(f"[\n{sym_report}\n].query('growth trends', prompt='Analyze the quarterly growth patterns')", performance_query, "query", "semantic") - - # Test convert method with different formats - sym_json_data = Symbol('{"name": "John", "age": 30, "city": "New York"}') - - yaml_converted = sym_json_data.convert("YAML") - display_op(f"[{sym_json_data}].convert('YAML')", yaml_converted, "convert", "semantic") - - xml_converted = sym_json_data.convert("XML") - display_op(f"[{sym_json_data}].convert('XML')", xml_converted, "convert", "semantic") - - # Test convert with tabular data - sym_csv_like = Symbol(dedent(""" - Name,Age,Department - Alice,28,Engineering - Bob,35,Marketing - Carol,42,Sales - """)) - - table_converted = sym_csv_like.convert("HTML table") - display_op(f"[\n{sym_csv_like}\n].convert('HTML table')", f"\n{table_converted}\n", "convert", "semantic") - - # Test convert with markdown format - sym_text = Symbol("This is a simple paragraph with some important information that needs formatting.") - markdown_converted = sym_text.convert("Markdown with bullet points") - display_op(f"[{sym_text}].convert('Markdown with bullet points')", markdown_converted, "convert", "semantic") - - # Test transcribe method with various modifications - sym_formal = Symbol("Hey there! How's it going? Hope you're doing well!") - - formal_transcribed = sym_formal.transcribe("make it formal and professional") - display_op(f"[{sym_formal}].transcribe('make it formal and professional')", formal_transcribed, "transcribe", "semantic") - - # Test transcribe with tone change - sym_technical = Symbol("The system crashed because of insufficient memory allocation and poor error handling.") - simple_transcribed = sym_technical.transcribe("explain in simple terms for non-technical audience") - display_op(f"[{sym_technical}].transcribe('explain in simple terms for non-technical audience')", simple_transcribed, "transcribe", "semantic") - - # Test transcribe with style modification - sym_boring = Symbol("The meeting will be held on Monday at 2 PM in conference room A.") - engaging_transcribed = sym_boring.transcribe("make it more engaging and friendly") - display_op(f"[{sym_boring}].transcribe('make it more engaging and friendly')", engaging_transcribed, "transcribe", "semantic") - - # Test transcribe with length modification - sym_verbose = Symbol(dedent(""" - In consideration of the aforementioned circumstances and taking into account - the various factors that have been discussed in previous meetings, it has - been determined that the most appropriate course of action would be to - proceed with the implementation of the proposed solution at the earliest - possible convenience, subject to the availability of necessary resources. - """)) - - concise_transcribed = sym_verbose.transcribe("make it concise and direct") - display_op(f"[\n{sym_verbose}\n].transcribe('make it concise and direct')", f"\n{concise_transcribed}\n", "transcribe", "semantic") - - # Test transcribe with language style change - sym_casual = Symbol("I think maybe we should probably consider looking into this issue sometime soon.") - confident_transcribed = sym_casual.transcribe("make it more confident and decisive") - display_op(f"[{sym_casual}].transcribe('make it more confident and decisive')", confident_transcribed, "transcribe", "semantic") - -@pytest.mark.mandatory -def test_execution_control_pr(): - """Test the ExecutionControlPrimitives class methods.""" - - # Test analyze method with exception handling - sym_code = Symbol("print('Hello World')") - try: - # Create a simple exception for testing - raise ValueError("Sample error for testing analyze method") - except Exception as e: - analyzed = sym_code.analyze(exception=e, query="What went wrong?") - display_op(f"[{sym_code}].analyze(exception={type(e).__name__}, query='What went wrong?')", analyzed, "analyze", "semantic") - - # Test execute method with simple code - sym_simple_code = Symbol(dedent(""" - def run(): - return 2 + 3 - res = run() - """)) - executed = sym_simple_code.execute() - display_op(f"[{sym_simple_code.value.strip()}].execute()", executed, "execute", "syntactic") - - # Test execute with more complex expression - sym_math_code = Symbol(dedent(""" - def run(): - import math - return math.sqrt(16) - res = run() - """)) - executed_math = sym_math_code.execute() - display_op(f"[{sym_math_code.value.strip()}].execute()", executed_math, "execute", "syntactic") - - # Test fexecute method (fallback execute) - sym_fallback = Symbol(dedent(""" - def run(): - return sum([1, 2, 3, 4]) - res = run() - """)) - fexecuted = sym_fallback.fexecute() - display_op(f"[{sym_fallback.value.strip()}].fexecute()", fexecuted, "fexecute", "syntactic") - - # Test simulate method (for code simulation) - sym_code = Symbol("x = 5; y = 10; result = x + y") - simulated = sym_code.simulate() - display_op(f"[{sym_code}].simulate()", simulated, "simulate", "semantic") - - # Test simulate with algorithm - sym_algorithm = Symbol("def fibonacci(n): return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)") - algorithm_sim = sym_algorithm.simulate() - display_op(f"[{sym_algorithm}].simulate()", algorithm_sim, "simulate", "semantic") - - # Test sufficient method - sym_info = Symbol(dedent(""" - Product Name: UltraBook Pro - Price: $1299 - RAM: 16GB - Storage: 512GB SSD - Screen: 15.6 inch - """)) - - sufficient_check = sym_info.sufficient("Is this enough information to make a purchase decision?") - display_op(f"[\n{sym_info}\n].sufficient('Is this enough information to make a purchase decision?')", sufficient_check, "sufficient", "semantic") - - # Test sufficient with incomplete information - sym_partial = Symbol("Name: John, Age: 30") - partial_sufficient = sym_partial.sufficient("Is this enough information for a job application?") - display_op(f"[{sym_partial}].sufficient('Is this enough information for a job application?')", partial_sufficient, "sufficient", "semantic") - - # Test list method - sym_employees = Symbol(dedent(""" - Employee List: - 2. Bob - Manager - $85000 - 3. Carol - Designer - $65000 - 4. David - Engineer - $72000 - 5. Eve - Manager - $90000 - """)) - - engineers_list = sym_employees.list("all employees who are engineers") - display_op(f"[\n{sym_employees}\n].list('employees who are engineers')", f"\n{engineers_list}\n", "list", "semantic") - - # Test list with salary condition - high_earners = sym_employees.list("employees earning less than $70000") - display_op(f"[\n{sym_employees}\n].list('employees earning less than $70000')", f"\n{high_earners}\n", "list", "semantic") - - # Test foreach method - sym_numbers = Symbol([1, 2, 3, 4, 5]) - squared_numbers = sym_numbers.foreach("each number", "square the number") - display_op(f"[{sym_numbers}].foreach('each number', 'square the number')", squared_numbers, "foreach", "semantic") - - # Test foreach with text processing - sym_sentences = Symbol(["hello world", "python programming", "artificial intelligence"]) - capitalized = sym_sentences.foreach("each sentence", "capitalize all words") - display_op(f"[{sym_sentences}].foreach('each sentence', 'capitalize all words')", capitalized, "foreach", "semantic") - - # Test stream method (basic example since it requires Expression objects) - try: - # Create a simple expression for streaming - class SimpleExpr(Expression): - def __init__(self): - super().__init__() - - def __call__(self, sym, **kwargs): - return Symbol(f"Processed: {sym.value}") - - sym_large_text = Symbol("This is a large text that needs to be processed in chunks for streaming.") - simple_expr = SimpleExpr() - - # Stream processing - streamed_results = list(sym_large_text.stream(simple_expr, token_ratio=0.8)) - display_op(f"[{sym_large_text}].stream(simple_expr, token_ratio=0.8)", f"Streamed {len(streamed_results)} chunks", "stream", "semantic") - except Exception as e: - print(f"Stream test encountered issue: {e}") - - # Test ftry method (fault-tolerant execution) - try: - class TestExpr(Expression): - def __init__(self, should_fail=False): - super().__init__() - self.should_fail = should_fail - self.attempt_count = 0 - - def __call__(self, sym, **kwargs): - self.attempt_count += 1 - if self.should_fail and self.attempt_count <= 1: - raise ValueError("Intentional failure for testing") - return Symbol(f"Success on attempt {self.attempt_count}: {sym.value}") - - sym_test = Symbol("test data") - failing_expr = TestExpr(should_fail=True) - - # Test ftry with retry logic - ftry_result = sym_test.ftry(failing_expr, retries=2) - display_op(f"[{sym_test}].ftry(failing_expr, retries=2)", ftry_result, "ftry", "semantic") - - # Test ftry with successful expression - success_expr = TestExpr(should_fail=False) - ftry_success = sym_test.ftry(success_expr, retries=1) - display_op(f"[{sym_test}].ftry(success_expr, retries=1)", ftry_success, "ftry", "semantic") - except Exception as e: - print(f"Ftry test encountered issue: {e}") - -@pytest.mark.mandatory -def test_dict_handling_pr(): - """Test the DictHandlingPrimitives class methods.""" - - # Test dict() method with basic text - sym_text = Symbol("I have apples, oranges, and bananas in my kitchen.") - dict_result = sym_text.dict("categorize fruits") - display_op(f"[{sym_text}].dict('categorize fruits')", dict_result, "dict", "semantic") - - # Test dict() method with shopping list - sym_shopping = Symbol("milk, bread, eggs, apples, cheese, chicken, broccoli, rice") - food_dict = sym_shopping.dict("organize by food categories") - display_op(f"[{sym_shopping}].dict('organize by food categories')", food_dict, "dict", "semantic") - - # Test dict() method with mixed data - sym_mixed = Symbol(dedent(""" - Alice works as an engineer and likes reading. - Bob is a manager who enjoys cooking. - Carol is a designer who loves painting. - """)) - people_dict = sym_mixed.dict("organize people by profession and hobbies") - display_op(f"[\n{sym_mixed}\n].dict('organize people by profession and hobbies')", f"\n{people_dict}\n", "dict", "semantic") - - # Test dict() method with numbers and context - sym_numbers = Symbol([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) - number_dict = sym_numbers.dict("classify numbers") - display_op(f"[{sym_numbers}].dict('classify numbers')", number_dict, "dict", "semantic") - - # Test dict() method with specific context and kwargs - sym_animals = Symbol("Dogs bark, cats meow, birds chirp, fish swim") - animal_dict = sym_animals.dict("group animals by sound", detailed=True) - display_op(f"[{sym_animals}].dict('group animals by sound', detailed=True)", animal_dict, "dict", "semantic") - - # Test dict() with complex structured text - sym_products = Symbol(dedent(""" - Laptop: $1200, Electronics - Book: $15, Education - Phone: $800, Electronics - Notebook: $5, Education - Tablet: $600, Electronics - """)) - product_dict = sym_products.dict("organize products by category and price range") - display_op(f"[\n{sym_products}\n].dict('organize products by category and price range')", f"\n{product_dict}\n", "dict", "semantic") - -@pytest.mark.mandatory -def test_template_styling_pr(): - """Test the TemplateStylingPrimitives class methods.""" - - # Test template() method with default placeholder - sym_name = Symbol("Alice") - template_str = "Hello {{placeholder}}, welcome to our service!" - templated_result = sym_name.template(template_str) - expected_result = "Hello Alice, welcome to our service!" - assert str(templated_result) == expected_result - display_op(f"[{sym_name}].template('{template_str}')", templated_result, "template", "syntactic") - - # Test template() method with custom placeholder - sym_product = Symbol("Premium Headphones") - custom_template = "Product: ***ITEM*** - Now available in store!" - custom_placeholder = "***ITEM***" - custom_templated = sym_product.template(custom_template, placeholder=custom_placeholder) - expected_custom = "Product: Premium Headphones - Now available in store!" - assert str(custom_templated) == expected_custom - display_op(f"[{sym_product}].template('{custom_template}', placeholder='{custom_placeholder}')", custom_templated, "template", "syntactic") - - # Test template() method with more complex template - sym_data = Symbol("Machine Learning") - complex_template = dedent(""" - Course: {{placeholder}} - Duration: 12 weeks - Level: Intermediate - Prerequisites: Basic Python knowledge - """).strip() - complex_templated = sym_data.template(complex_template) - expected_complex = dedent(""" - Course: Machine Learning - Duration: 12 weeks - Level: Intermediate - Prerequisites: Basic Python knowledge - """).strip() - assert str(complex_templated) == expected_complex - display_op(f"[{sym_data}].template(complex_template)", f"\n{complex_templated}", "template", "syntactic") - - # Test template() method with numeric data - sym_number = Symbol(42) - number_template = "The answer to life, universe and everything is {{placeholder}}." - number_templated = sym_number.template(number_template) - expected_number = "The answer to life, universe and everything is 42." - assert str(number_templated) == expected_number - display_op(f"[{sym_number}].template('{number_template}')", number_templated, "template", "syntactic") - - # Test template() method with list data - sym_list = Symbol(["apple", "banana", "cherry"]) - list_template = "Available fruits: {{placeholder}}" - list_templated = sym_list.template(list_template) - expected_list = "Available fruits: ['apple', 'banana', 'cherry']" - assert str(list_templated) == expected_list - display_op(f"[{sym_list}].template('{list_template}')", list_templated, "template", "syntactic") - - # Test style() method with basic styling - sym_content = Symbol("This is a basic text that needs styling.") - style_description = "Make this text bold and italic" - styled_result = sym_content.style(style_description) - display_op(f"[{sym_content}].style('{style_description}')", styled_result, "style", "semantic") - - # Test style() method with libraries parameter - sym_code = Symbol("print('Hello World')") - code_style_description = "Format as Python code with syntax highlighting" - code_libraries = ["python", "syntax-highlighting"] - styled_code = sym_code.style(code_style_description, libraries=code_libraries) - display_op(f"[{sym_code}].style('{code_style_description}', libraries={code_libraries})", styled_code, "style", "semantic") - - # Test style() method with more complex styling - sym_text = Symbol("The quick brown fox jumps over the lazy dog.") - complex_style_description = "Transform into a professional headline format" - complex_styled = sym_text.style(complex_style_description) - display_op(f"[{sym_text}].style('{complex_style_description}')", complex_styled, "style", "semantic") - - # Test style() method with empty libraries list - sym_simple = Symbol("Simple text") - simple_style_description = "Make this text more engaging" - simple_styled = sym_simple.style(simple_style_description, libraries=[]) - display_op(f"[{sym_simple}].style('{simple_style_description}', libraries=[])", simple_styled, "style", "semantic") - - # Test template() method with edge cases - sym_empty = Symbol("") - empty_template = "Empty content: {{placeholder}}" - empty_templated = sym_empty.template(empty_template) - expected_empty = "Empty content: " - assert str(empty_templated) == expected_empty - display_op(f"[{sym_empty}].template('{empty_template}')", empty_templated, "template", "syntactic") - - # Test template() method with no placeholder in template - sym_no_placeholder = Symbol("test") - no_placeholder_template = "This template has no placeholder" - no_placeholder_result = sym_no_placeholder.template(no_placeholder_template) - expected_no_placeholder = "This template has no placeholder" - assert str(no_placeholder_result) == expected_no_placeholder - display_op(f"[{sym_no_placeholder}].template('{no_placeholder_template}')", no_placeholder_result, "template", "syntactic") - - # Test template() method with multiple placeholders - sym_multi = Symbol("Python") - multi_template = "Language: {{placeholder}}, Type: {{placeholder}}, Popularity: High" - multi_templated = sym_multi.template(multi_template) - expected_multi = "Language: Python, Type: Python, Popularity: High" - assert str(multi_templated) == expected_multi - display_op(f"[{sym_multi}].template('{multi_template}')", multi_templated, "template", "syntactic") - -@pytest.mark.mandatory -@pytest.mark.skipif(not SYMAI_CONFIG.get('EMBEDDING_ENGINE_MODEL', False) and not SYMAI_CONFIG.get('EMBEDDING_ENGINE_API_KEY', False), reason="Embedding engine not configured!") -def test_data_clustering_pr(): - """Test the DataClusteringPrimitives class methods.""" - # Test cluster method with simple text data - sym_text = Symbol(["apple", "banana", "cherry", "apple", "orange", "banana", "grape"]) - clustered_result = sym_text.cluster(metric='cosine', min_cluster_size=2) - display_op(f"[{sym_text}].cluster(metric='cosine', min_cluster_size=2)", clustered_result, "cluster", "semantic") - - # Test cluster method with list data - sym_list = Symbol(["technology", "science", "programming", "coding", "research", "innovation"]) - clustered_list = sym_list.cluster() - display_op(f"[{sym_list}].cluster()", clustered_list, "cluster", "semantic") - - # Test cluster method with structured sentences - sym_sentences = Symbol([ - 'The concert last night was absolutely incredible!', - 'That was the worst experience of my life.', - 'I can’t stop smiling after tasting that delicious cake.', - 'I hate how poorly designed this device is.', - 'What a fantastic day at the beach with friends!', - 'This traffic jam is driving me insane.', - 'This new book has completely captivated me.', - 'I fucking despise waiting in long lines.' - ]) - clustered_sentences = sym_sentences.cluster(min_cluster_size=3) - display_op(f"[{sym_sentences}].cluster(min_cluster_size=3)", clustered_sentences, "cluster", "semantic") - - # Test cluster method with simple categories - sym_categories = Symbol([ - "cat", "dog", "fish", "bird", - "car", "truck", "bicycle", "motorcycle", - "apple", "banana", "orange", "grape" - ]) - clustered_categories = sym_categories.cluster(metric='cosine', min_cluster_size=2) - display_op(f"[{sym_categories}].cluster(metric='cosine', min_cluster_size=2)", clustered_categories, "cluster", "semantic") - -@pytest.mark.mandatory -@pytest.mark.skipif(not SYMAI_CONFIG.get('EMBEDDING_ENGINE_MODEL', False) and not SYMAI_CONFIG.get('EMBEDDING_ENGINE_API_KEY', False), reason="Embedding engine not configured!") -def test_embedding_pr(): - """Test the EmbeddingPrimitives class methods.""" - - # Test embed() method with simple string - sym_text = Symbol("hello world") - embedded_result = sym_text.embed() - display_op(f"[{sym_text}].embed()", f"embeddings shape: {np.array(embedded_result.value).shape}", "embed", "semantic") - - # Test embedding property - embedding_value = sym_text.embedding - display_op(f"[{sym_text}].embedding", f"embedding shape: {embedding_value.shape}", "embedding", "semantic") - assert isinstance(embedding_value, np.ndarray) - - # Test similarity with same string (edge case - should be 1.0 or very close) - sym_same = Symbol("hello world") - similarity_result = sym_text.similarity(sym_same) - display_op(f"[{sym_text}].similarity([{sym_same}])", similarity_result, "similarity", "semantic") - assert isinstance(similarity_result, float) - assert similarity_result > 0.99 # Should be very close to 1.0 for identical strings - - # Test distance with same string (edge case - should be 0.0 or very close for distance measures) - distance_result = sym_text.distance(sym_same, kernel='cosine') - display_op(f"[{sym_text}].distance([{sym_same}], kernel='cosine')", distance_result, "distance", "semantic") - assert isinstance(distance_result, float) - assert distance_result < 0.01 # Should be very close to 0.0 for identical strings - - # Test zip method with string - check format - zip_result = sym_text.zip() - display_op(f"[{sym_text}].zip()", f"zip format: {type(zip_result)}, length: {len(zip_result)}", "zip", "semantic") - - # Syntactic checks for zip format - assert isinstance(zip_result, list), "zip() should return a list" - assert len(zip_result) == 1, "single string should result in list of length 1" - - # Check tuple structure - tuple_item = zip_result[0] - assert isinstance(tuple_item, tuple), "each item should be a tuple" - assert len(tuple_item) == 3, "each tuple should have 3 elements (id, embedding, query)" - - # Check tuple element types - idx, embedding, query = tuple_item - assert isinstance(idx, str), "first element should be string ID" - assert isinstance(embedding, list), "second element should be embedding as list" - assert isinstance(query, dict), "third element should be query dict" - assert 'text' in query, "query dict should contain 'text' key" - assert query['text'] == 'hello world', "query text should match original value" - - # Test zip with list of strings - sym_list = Symbol([["apple"], ["banana"]]) - zip_list_result = sym_list.zip() - display_op(f"[{sym_list}].zip()", f"zip format: {type(zip_list_result)}, length: {len(zip_list_result)}", "zip", "semantic") - - # Check each tuple in the list - for i, (idx, embedding, query) in enumerate(zip_list_result): - assert isinstance(idx, str) - assert isinstance(embedding, list) - assert isinstance(query, dict) - assert 'text' in query - assert query['text'] == str([['apple', 'banana'][i]]) - - # Test similarity with different metrics - sym_other = Symbol("different text") - cosine_sim = sym_text.similarity(sym_other, metric='cosine') - product_sim = sym_text.similarity(sym_other, metric='product') - display_op(f"[{sym_text}].similarity([{sym_other}], metric='cosine')", cosine_sim, "similarity", "semantic") - display_op(f"[{sym_text}].similarity([{sym_other}], metric='product')", product_sim, "similarity", "semantic") - - # Test distance with different kernels - gaussian_dist = sym_text.distance(sym_other, kernel='gaussian') - linear_dist = sym_text.distance(sym_other, kernel='linear') - display_op(f"[{sym_text}].distance([{sym_other}], kernel='gaussian')", gaussian_dist, "distance", "semantic") - display_op(f"[{sym_text}].distance([{sym_other}], kernel='linear')", linear_dist, "distance", "semantic") - - # Test error handling for zip method - sym_invalid = Symbol(123) - try: - sym_invalid.zip() - assert False, "zip() should raise ValueError for non-string/non-list input" - except ValueError as e: - display_op(f"[{sym_invalid}].zip()", f"ValueError: {str(e)}", "zip", "syntactic") - assert "Expected id to be a string" in str(e) - -@pytest.mark.mandatory -def test_io_handling_pr(): - """Test the IOHandlingPrimitives class methods.""" - - # Test open() method with path as parameter - with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as tmp_file: - test_content = "Hello, this is test content for file operations." - tmp_file.write(test_content) - tmp_file_path = tmp_file.name - - try: - # Test opening file with path parameter - sym_empty = Symbol() - opened_result = sym_empty.open(tmp_file_path) - display_op(f"Symbol().open('{os.path.basename(tmp_file_path)}')", f"content length: {len(opened_result.value)}", "open", "syntactic") - assert isinstance(opened_result.value, str) - assert test_content in opened_result.value - - # Test opening file with path as Symbol value - sym_path = Symbol(tmp_file_path) - opened_from_value = sym_path.open() - display_op(f"Symbol('{os.path.basename(tmp_file_path)}').open()", f"content length: {len(opened_from_value.value)}", "open", "syntactic") - assert isinstance(opened_from_value.value, str) - assert test_content in opened_from_value.value - - finally: - if os.path.exists(tmp_file_path): - os.unlink(tmp_file_path) - - # Test error handling for open() method with no path - sym_no_path = Symbol() - try: - sym_no_path.open() - assert False, "open() should raise ValueError when no path is provided" - except ValueError as e: - display_op(f"Symbol().open()", f"ValueError: {str(e)}", "open", "syntactic") - assert "Path is not provided" in str(e) - - assert hasattr(sym_no_path, 'input'), "Symbol should have input method" - assert callable(getattr(sym_no_path, 'input')), "input should be callable" - display_op(f"Symbol().input()", "input method is callable (requires interaction)", "input", "syntactic") - -@pytest.mark.mandatory -def test_persistence_pr(): - """Test the PersistencePrimitives class methods.""" - import pickle - - # Test save() and load() methods with serialization - sym_test = Symbol("Hello, persistence test!") - - # Create a temporary file path (but delete the file so save can create it properly) - with tempfile.NamedTemporaryFile(delete=False, suffix='.pkl') as tmp_file: - tmp_file_path = tmp_file.name - os.unlink(tmp_file_path) # Remove the empty file - - try: - # Test save with serialize=True (default) - sym_test.save(tmp_file_path, serialize=True) - display_op(f"Symbol('{sym_test}').save('{os.path.basename(tmp_file_path)}', serialize=True)", "saved as pickle", "save", "syntactic") - - # Check that pickle file was created - pkl_path = tmp_file_path + '.pkl' if not tmp_file_path.endswith('.pkl') else tmp_file_path - assert os.path.exists(pkl_path), "Pickle file should be created" - - # Test load() method - now it's an instance method, not static - loader_sym = Symbol() - loaded_sym = loader_sym.load(pkl_path) - display_op(f"Symbol().load('{os.path.basename(pkl_path)}')", f"loaded: {loaded_sym.value}", "load", "syntactic") - assert isinstance(loaded_sym, Symbol) - assert loaded_sym.value == sym_test.value - - finally: - # Cleanup - for path in [tmp_file_path, tmp_file_path + '.pkl']: - if os.path.exists(path): - os.unlink(path) - - # Test save() with serialize=False - with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as tmp_file: - tmp_file_path = tmp_file.name - os.unlink(tmp_file_path) # Remove the empty file - - try: - sym_text = Symbol("This is a text save test") - sym_text.save(tmp_file_path, serialize=False) - display_op(f"Symbol('{sym_text}').save('{os.path.basename(tmp_file_path)}', serialize=False)", "saved as text", "save", "syntactic") - - # Read the file to verify content - with open(tmp_file_path, 'r') as f: - saved_content = f.read() - assert saved_content == str(sym_text) - - finally: - if os.path.exists(tmp_file_path): - os.unlink(tmp_file_path) - - # Test save() with replace=False (default) - should create new file - with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as tmp_file: - base_path = tmp_file.name - tmp_file.write("existing content") - - try: - sym_replace = Symbol("new content") - sym_replace.save(base_path, serialize=False, replace=False) - display_op(f"Symbol('{sym_replace}').save(existing_file, serialize=False, replace=False)", "created new file with suffix", "save", "syntactic") - - # Should create a file with _0 suffix - expected_new_path = base_path.replace('.txt', '_0.txt') - assert os.path.exists(expected_new_path), "New file with suffix should be created" - - with open(expected_new_path, 'r') as f: - content = f.read() - assert content == str(sym_replace) - - # Clean up the _0 file - os.unlink(expected_new_path) - - finally: - if os.path.exists(base_path): - os.unlink(base_path) - - # Test save() with replace=True - should overwrite existing file - with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as tmp_file: - replace_base_path = tmp_file.name - tmp_file.write("original content") - - try: - sym_replace_true = Symbol("overwritten content") - sym_replace_true.save(replace_base_path, serialize=False, replace=True) - display_op(f"Symbol('{sym_replace_true}').save(existing_file, serialize=False, replace=True)", "overwritten existing file", "save", "syntactic") - - # Should overwrite the original file, not create a new one - with open(replace_base_path, 'r') as f: - content = f.read() - assert content == str(sym_replace_true), "File content should be overwritten" - - # Verify that no _0 suffix file was created - expected_suffix_path = replace_base_path.replace('.txt', '_0.txt') - assert not os.path.exists(expected_suffix_path), "No suffix file should be created when replace=True" - - finally: - if os.path.exists(replace_base_path): - os.unlink(replace_base_path) - - # Test expand() method functionality - sym_expand = Symbol("Calculate the fibonacci sequence up to 10 numbers") - - try: - # Test expand method - it should return a function name - func_name = sym_expand.expand() - display_op(f"Symbol('{sym_expand}').expand()", f"generated function: {func_name}", "expand", "semantic") - - # Check that expand returns a string (function name) - assert isinstance(func_name, str), "expand() should return a function name as string" - assert len(func_name) > 0, "function name should not be empty" - - # Check that the function was added as an attribute to the Symbol - assert hasattr(sym_expand, func_name), f"Symbol should have the generated function '{func_name}' as attribute" - assert callable(getattr(sym_expand, func_name)), f"Generated function '{func_name}' should be callable" - - except Exception as e: - # If expand fails due to missing LLM configuration, that's expected - display_op(f"Symbol('{sym_expand}').expand()", f"Error (expected if LLM not configured): {type(e).__name__}", "expand", "semantic") - - # Test expand with different problem - sym_math = Symbol("Write a function to calculate square root") - try: - math_func_name = sym_math.expand() - display_op(f"Symbol('{sym_math}').expand()", f"generated function: {math_func_name}", "expand", "semantic") - assert isinstance(math_func_name, str) - assert hasattr(sym_math, math_func_name) - - except Exception as e: - display_op(f"Symbol('{sym_math}').expand()", f"Error (expected if LLM not configured): {type(e).__name__}", "expand", "semantic") - -@pytest.mark.mandatory -def test_output_handling_pr(): - """Test the OutputHandlingPrimitives class methods.""" - - # Test basic output() method functionality - sym_test = Symbol("Hello, output test!") - - # Test output method with default parameters - result = sym_test.output() - display_op(f"Symbol('{sym_test}').output()", result, "output", "syntactic") - assert isinstance(result, Symbol) - - # Test output method with custom handler function - captured_output = [] - def custom_handler(input_dict): - captured_output.append(input_dict) - - result_with_handler = sym_test.output(handler=custom_handler) - display_op(f"Symbol('{sym_test}').output(handler=custom_handler)", result_with_handler, "output", "syntactic") - assert isinstance(result_with_handler, Symbol) - - # Test output method with additional args - result_with_args = sym_test.output("arg1", "arg2") - display_op(f"Symbol('{sym_test}').output('arg1', 'arg2')", result_with_args, "output", "syntactic") - assert isinstance(result_with_args, Symbol) - - # Test output method with kwargs - result_with_kwargs = sym_test.output(custom_param="value") - display_op(f"Symbol('{sym_test}').output(custom_param='value')", result_with_kwargs, "output", "syntactic") - assert isinstance(result_with_kwargs, Symbol) - - # Verify that output method exists and is callable - assert hasattr(sym_test, 'output'), "Symbol should have output method" - assert callable(getattr(sym_test, 'output')), "output should be callable" - - # Test with different symbol types - sym_number = Symbol(42) - num_result = sym_number.output() - display_op(f"Symbol({sym_number}).output()", num_result, "output", "syntactic") - assert isinstance(num_result, Symbol) - - sym_test = Symbol("Hello, dual args test!", test_kwarg={'processed': "Hello, dual args test!"}) - # This should show both function call args (in processed) and expression args (in args field) - result = sym_test.output("call_arg1", "call_arg2") - - display_op( - f"Symbol('{sym_test}').output('call_arg1', 'call_arg2')", - result, - "output", - "syntactic" - ) - - assert "Hello, dual args test!" in str(result.value['processed']) - assert isinstance(result, Symbol) - - # Test with no arguments to show the difference - result_no_args = sym_test.output() - display_op( - f"Symbol('{sym_test}').output()", - result_no_args, - "output", - "syntactic" - ) - - assert "Hello, dual args test!" in str(result_no_args.value['processed']) diff --git a/symbolicai-main/symbolicai-main/trusted_repos.yml b/symbolicai-main/symbolicai-main/trusted_repos.yml deleted file mode 100644 index 752fd524e7b0fb12c983ab2ac7be18f67c289331..0000000000000000000000000000000000000000 --- a/symbolicai-main/symbolicai-main/trusted_repos.yml +++ /dev/null @@ -1,34 +0,0 @@ -repositories: - - repo: - name: "ExtensityAI/embeddings" - desc: "Embeddings based on the Sentence Transformers repository" - - repo: - name: "ExtensityAI/fullmetalshell" - desc: "Shell Style replies like the Drill Sergeant from Full Metal Jacket" - - repo: - name: "ExtensityAI/rickshell" - desc: "Shell Style replies like in Rick and Morty" - - repo: - name: "ExtensityAI/llamaswithshell" - desc: "Shell Style replies like in Llamas With Hats" - - repo: - name: "ExtensityAI/bigbangshell" - desc: "Get help from the most profound Shell-don AI out there" - - repo: - name: "ExtensityAI/symscribe" - desc: "A repository for transcribing audio files using Whisper." - - repo: - name: "ExtensityAI/timezone" - desc: "Timezone converter" - - repo: - name: "ExtensityAI/releasenote" - desc: "Release note generator" - - repo: - name: "ExtensityAI/symmail" - desc: "Email generator" - - repo: - name: "ExtensityAI/symask" - desc: "Shell Q&A prototype bot" - - repo: - name: "ExtensityAI/codegen" - desc: "Shell code generator bot" \ No newline at end of file