File size: 5,387 Bytes
49b0a2d
 
 
4f8926e
 
 
e6d4ed8
49b0a2d
 
 
 
818f521
86a4cb8
818f521
49b0a2d
86a4cb8
 
 
 
 
49b0a2d
 
86a4cb8
 
 
49b0a2d
86a4cb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3eafa3a
86a4cb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49b0a2d
84357ab
49b0a2d
 
 
 
 
 
86a4cb8
49b0a2d
 
84357ab
49b0a2d
4f8926e
b65033f
49b0a2d
 
 
 
 
46b4ee6
49b0a2d
 
31be0ff
49b0a2d
35cdc9b
49b0a2d
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import os
from typing import Optional
from pydantic import Field, BaseModel
from omegaconf import OmegaConf

from llama_index.core.utilities.sql_wrapper import SQLDatabase
from sqlalchemy import create_engine

from dotenv import load_dotenv
load_dotenv(override=True)

from vectara_agentic.agent import Agent
from vectara_agentic.agent_config import AgentConfig
from vectara_agentic.tools import ToolsFactory, VectaraToolFactory

class AgentTools:
    def __init__(self, _cfg, agent_config):
        self.tools_factory = ToolsFactory()
        self.agent_config = agent_config
        self.cfg = _cfg


    def get_tools(self):
        class QueryElectricCars(BaseModel):
            query: str = Field(description="The user query.")

        vec_factory_1 = VectaraToolFactory(vectara_api_key=self.cfg.api_keys[0],
                                            vectara_corpus_key=self.cfg.corpus_keys[0])
        
        summarizer = 'vectara-experimental-summary-ext-2023-12-11-med-omni'

        ask_vehicles = vec_factory_1.create_rag_tool(
            tool_name = "ask_vehicles",
            tool_description = """
            Given a user query, 
            returns a response to a user question about electric vehicles.
            """,
            tool_args_schema = QueryElectricCars,
            reranker = "chain", rerank_k = 100,
            rerank_chain = [
                {
                    "type": "slingshot",
                    "cutoff": 0.2
                },
                {
                    "type": "mmr",
                    "diversity_bias": 0.1
                }
            ],
            n_sentences_before = 2, n_sentences_after = 2, lambda_val = 0.005,
            summary_num_results = 5,
            vectara_summarizer = summarizer,
            include_citations = False,
        )

        vec_factory_2 = VectaraToolFactory(vectara_api_key=self.cfg.api_keys[1],
                                        vectara_corpus_key=self.cfg.corpus_keys[1])
        

        class QueryEVLaws(BaseModel):
            query: str = Field(description="The user query")
            state: Optional[str] = Field(default=None,
                                        description="The two digit state code. Optional.",
                                        examples=['CA', 'US', 'WA'])
            policy_type: Optional[str] = Field(default=None,
                                            description="The type of policy. Optional",
                                            examples = ['Laws and Regulations', 'State Incentives', 'Incentives', 'Utility / Private Incentives', 'Programs'])
            

        ask_policies = vec_factory_2.create_rag_tool(
            tool_name = "ask_policies",
            tool_description = """
            Given a user query,
            returns a response to a user question about electric vehicles incentives and regulations, in the United States.
            You can ask this tool any question about laws passed by states or the federal government related to electric vehicles.
            """,
            tool_args_schema = QueryEVLaws,
            reranker = "chain", rerank_k = 100, 
            rerank_chain = [
                {
                    "type": "slingshot",
                    "cutoff": 0.2
                },
                {
                    "type": "mmr",
                    "diversity_bias": 0.1
                }
            ],
            n_sentences_before = 2, n_sentences_after = 2, lambda_val = 0.005,
            summary_num_results = 10,
            vectara_summarizer = summarizer,
            include_citations = False,
        )

        tools_factory = ToolsFactory()

        db_tools = tools_factory.database_tools(
                    tool_name_prefix = "ev",
                    content_description = 'Electric Vehicles in the state of Washington and other population information',
                    sql_database = SQLDatabase(create_engine('sqlite:///ev_database.db')),
                )

        return (tools_factory.standard_tools() + 
                tools_factory.guardrail_tools() +
                db_tools +
                [ask_vehicles, ask_policies]
        )

def initialize_agent(_cfg, agent_progress_callback=None):
    electric_vehicle_bot_instructions = """
    - You are a helpful research assistant, with expertise in electric vehicles, in conversation with a user.
    - Never discuss politics, and always respond politely.
    """

    agent = Agent(
        tools=AgentTools(_cfg, AgentConfig()).get_tools(),
        topic="Electric vehicles in the United States",
        custom_instructions=electric_vehicle_bot_instructions,
        agent_progress_callback=agent_progress_callback
    )
    agent.report()

    return agent


def get_agent_config() -> OmegaConf:
    cfg = OmegaConf.create({
        'corpus_keys': str(os.environ['VECTARA_CORPUS_KEYS']).split(','),
        'api_keys': str(os.environ['VECTARA_API_KEYS']).split(','),
        'examples': os.environ.get('QUERY_EXAMPLES', None),
        'demo_name': "ev-assistant",
        'demo_welcome': "Welcome to the EV Assistant demo.",
        'demo_description': "This assistant can help you learn about electric vehicles in the United States, including how they work, the advantages of purchasing them, and recent trends based on data in the state of Washington.",
    })
    return cfg