How to use the parlai.core.agents.Agent function in parlai

To help you get started, we’ve selected a few parlai examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github facebookresearch / ParlAI / projects / personachat / kvmemnn / kvmemnn.py View on Github external
cands = []
                if lines_have_ids:
                    space_idx = line.find(' ')
                    line = line[space_idx + 1 :]
                    if cands_are_replies:
                        sp = line.split('\t')
                        if len(sp) > 1 and sp[1] != '':
                            cands.append(sp[1])
                    else:
                        cands.append(line)
                else:
                    cands.append(line)
    return cands


class KvmemnnAgent(Agent):
    """Simple implementation of the memnn algorithm with 1 hop
    """

    OPTIM_OPTS = {
        'adadelta': optim.Adadelta,
        'adagrad': optim.Adagrad,
        'adam': optim.Adam,
        'adamax': optim.Adamax,
        'asgd': optim.ASGD,
        'lbfgs': optim.LBFGS,
        'rmsprop': optim.RMSprop,
        'rprop': optim.Rprop,
        'sgd': optim.SGD,
    }

    @staticmethod
github WattSocialBot / alana_learning_to_rank / alana_learning_to_rank / kvmemnn_agent.py View on Github external
cands = []
                if lines_have_ids:
                    space_idx = line.find(' ')
                    line = line[space_idx + 1:]
                    if cands_are_replies:
                        sp = line.split('\t')
                        if len(sp) > 1 and sp[1] != '':
                            cands.append(sp[1])
                    else:
                        cands.append(line)
                else:
                    cands.append(line)
    return cands


class KvmemnnAgent(Agent):
    """Simple implementation of the memnn algorithm with 1 hop
    """

    OPTIM_OPTS = {
        'adadelta': optim.Adadelta,
        'adagrad': optim.Adagrad,
        'adam': optim.Adam,
        'adamax': optim.Adamax,
        'asgd': optim.ASGD,
        'lbfgs': optim.LBFGS,
        'rmsprop': optim.RMSprop,
        'rprop': optim.Rprop,
        'sgd': optim.SGD,
    }

    @staticmethod
github deepmipt / kpi2017 / deeppavlov / agents / insults / insults_agents.py View on Github external
import copy
from parlai.core.agents import Agent
from . import config
from .model import InsultsModel
from .utils import create_vectorizer_selector, get_vectorizer_selector
from .embeddings_dict import EmbeddingsDict

class EnsembleInsultsAgent(Agent):

    @staticmethod
    def add_cmdline_args(argparser):
        config.add_cmdline_args(argparser)
        ensemble = argparser.add_argument_group('Ensemble parameters')
        ensemble.add_argument('--model_files', type=str, default=None, nargs='+',
                              help='list of all the model files for the ensemble')
        ensemble.add_argument('--model_names', type=str, default=None, nargs='+',
                              help='list of all the model names for the ensemble')
        ensemble.add_argument('--model_coefs', type=str, default=None, nargs='+',
                              help='list of all the model coefs for the ensemble')

    def __init__(self, opt, shared=None):
        self.id = 'InsultsAgent'
        self.episode_done = True
        super().__init__(opt, shared)
github facebookresearch / ParlAI / parlai / mturk / core / dev / agents.py View on Github external
"""Return True if the assignment is in a final status that
        can no longer be acted on.
        """
        return (
            self.status == self.STATUS_DISCONNECT
            or self.status == self.STATUS_DONE
            or self.status == self.STATUS_PARTNER_DISCONNECT
            or
            # TODO REMOVE THIS TYPE
            self.status == self.STATUS_PARTNER_DISCONNECT_EARLY
            or self.status == self.STATUS_RETURNED
            or self.status == self.STATUS_EXPIRED
        )


class MTurkAgent(Agent):
    """Base class for an MTurkAgent that can act in a ParlAI world"""

    # MTurkAgent Possible Statuses
    ASSIGNMENT_NOT_DONE = 'NotDone'
    ASSIGNMENT_DONE = 'Submitted'
    ASSIGNMENT_APPROVED = 'Approved'
    ASSIGNMENT_REJECTED = 'Rejected'

    MTURK_DISCONNECT_MESSAGE = MTURK_DISCONNECT_MESSAGE
    TIMEOUT_MESSAGE = TIMEOUT_MESSAGE
    RETURN_MESSAGE = RETURN_MESSAGE

    def __init__(self, opt, mturk_manager, hit_id, assignment_id, worker_id):
        super().__init__(opt)

        # all MTurkManager functions explicitly used by agents extracted here
github facebookresearch / ParlAI / parlai / agents / local_human / local_human.py View on Github external
#!/usr/bin/env python3

# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Agent does gets the local keyboard input in the act() function.
   Example: python examples/eval_model.py -m local_human -t babi:Task1k:1 -dt valid
"""

from parlai.core.agents import Agent
from parlai.core.utils import display_messages, load_cands


class LocalHumanAgent(Agent):
    def add_cmdline_args(argparser):
        """Add command-line arguments specifically for this agent."""
        agent = argparser.add_argument_group('Local Human Arguments')
        agent.add_argument(
            '-fixedCands',
            '--local-human-candidates-file',
            default=None,
            type=str,
            help='File of label_candidates to send to other agent',
        )
        agent.add_argument(
            '--single_turn',
            type='bool',
            default=False,
            help='If on, assumes single turn episodes.',
        )
github deepmipt / hcn-dialogue-manager / hcn / agents / hcn / hcn.py View on Github external
import re

from parlai.core.agents import Agent, create_agent
from parlai.core.params import ParlaiParser

from . import config
from . import tracker
from . import templates as tmpl
from .emb_dict import EmbeddingsDict
from .model import HybridCodeNetworkModel
from .preprocess import HCNPreprocessAgent
from .utils import is_silence, is_null_api_answer, is_api_answer
from .metrics import DialogMetrics


class HybridCodeNetworkAgent(Agent):

    @staticmethod
    def add_cmdline_args(argparser):
        config.add_cmdline_args(argparser)
        HybridCodeNetworkAgent.dictionary_class().add_cmdline_args(argparser)
        argparser.add_argument('--debug', action='store_true',
                               help='Print debug output.')
        return argparser

    @staticmethod
    def dictionary_class():
        return HCNPreprocessAgent

    def __init__(self, opt, shared=None):
        if opt['numthreads'] > 1:
            raise RuntimeError("numthreads > 1 not supported for this model.")
github facebookresearch / ParlAI / parlai / agents / repeat_label / repeat_label.py View on Github external
Options:

    ``returnOneRandomAnswer`` -- default ``True``, set to ``False`` to instead
    reply with all labels joined by commas.

    ``cantAnswerPercent`` -- default ``0``, set value in range[0,1] to set
    chance of replying with "I don't know."
"""

import random

from parlai.core.agents import Agent


class RepeatLabelAgent(Agent):
    @staticmethod
    def add_cmdline_args(argparser):
        group = argparser.add_argument_group('RepeatLabel Arguments')
        group.add_argument(
            '--return_one_random_answer',
            type='bool',
            default=True,
            help='return one answer from the set of labels',
        )
        group.add_argument(
            '--cant_answer_percent',
            type=float,
            default=0,
            help='set value in range[0,1] to set chance of '
            'replying with special message',
        )
github deepmipt / kpi2017 / deeppavlov / agents / coreference / RepeatLabelAgent.py View on Github external
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from parlai.core.agents import Agent

class RepeatLabelAgent(Agent):
    # #
    # initialize by setting id
    # #
    def __init__(self, opt):
        self.id = 'LabelAgent'
    # #
    # store observation for later, return it unmodified
    # #
    def observe(self, observation):
        self.observation = observation
        return observation
    # #
    # return label from before if available
    # #
    def act(self):
        reply = self.observation
github facebookresearch / ParlAI / parlai / mturk / core / agents.py View on Github external
'HIT if you would like to try again'
            )
        else:
            # We shouldn't be getting an inactive command for the other
            # states so consider this a server error
            text = (
                'Our server was unable to handle your reconnect properly '
                'and thus this HIT no longer seems available for '
                'completion. Please try to connect again or return this '
                'HIT and accept a new one.'
            )

        return text, command


class MTurkAgent(Agent):
    """Base class for an MTurkAgent that can act in a ParlAI world"""

    # MTurkAgent Possible Statuses
    ASSIGNMENT_NOT_DONE = 'NotDone'
    ASSIGNMENT_DONE = 'Submitted'
    ASSIGNMENT_APPROVED = 'Approved'
    ASSIGNMENT_REJECTED = 'Rejected'

    MTURK_DISCONNECT_MESSAGE = MTURK_DISCONNECT_MESSAGE
    TIMEOUT_MESSAGE = TIMEOUT_MESSAGE
    RETURN_MESSAGE = RETURN_MESSAGE

    def __init__(self, opt, mturk_manager, hit_id, assignment_id, worker_id):
        super().__init__(opt)

        self.conversation_id = None
github facebookresearch / ParlAI / parlai / agents / drqa / drqa.py View on Github external
for token in tokens:
            if self.embedding_words is not None and token not in self.embedding_words:
                continue
            self.freq[token] += 1
            if token not in self.tok2ind:
                index = len(self.tok2ind)
                self.tok2ind[token] = index
                self.ind2tok[index] = token


# ------------------------------------------------------------------------------
# Document Reader.
# ------------------------------------------------------------------------------


class DrqaAgent(Agent):
    @staticmethod
    def add_cmdline_args(argparser):
        config.add_cmdline_args(argparser)
        DrqaAgent.dictionary_class().add_cmdline_args(argparser)

    @staticmethod
    def dictionary_class():
        return SimpleDictionaryAgent

    def __init__(self, opt, shared=None):
        if opt.get('numthreads', 1) > 1:
            raise RuntimeError("numthreads > 1 not supported for this model.")
        super().__init__(opt, shared)

        # All agents keep track of the episode (for multiple questions)
        self.episode_done = True