No edit summary
No edit summary
Line 1: Line 1:
import re, json, os, sys
import os, io, sys, re, json, base64
import instructor
import boto3
from ast import literal_eval
from operator import itemgetter
from langchain.agents import AgentExecutor, create_react_agent
from langchain_experimental.utilities import PythonREPL
from langchain.agents import Tool
from langchain_aws import ChatBedrock
#from langchain_community.chat_models import BedrockChat
from operator import itemgetter
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
from langchain.agents import AgentExecutor, create_react_agent
from langchain_experimental.utilities import PythonREPL
from langchain.agents import Tool
from langchain_aws import ChatBedrock
#from src.backend.llm.prompts import simple_extraction_prompt, complex_extraction_prompt, simple_or_complex_prompt, decomp_prompt, agent_prompt
from langchain_community.document_loaders import UnstructuredExcelLoader
from azure.identity import DefaultAzureCredential
# os.environ["OPENAI_API_TYPE"] = "azure_ad"
# os.environ["OPENAI_API_KEY"] = credential.get_token("https://cognitiveservices.azure.com/.default").token
from azure.identity import ChainedTokenCredential, ManagedIdentityCredential, AzureCliCredential
from langchain_openai import AzureOpenAI
from openai import AzureOpenAI
import openai
import openai
import requests
client = AzureOpenAI(api_key=os.getenv("AZURE_OPENAI_API_KEY"),api_version=os.getenv("AZURE_OPENAI_API_VERSION"),azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"))
from graphviz import Digraph
client = AzureOpenAI(api_key=os.getenv("AZURE_OPENAI_API_KEY"),api_version="2024-05-01-preview",azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"))
from langchain_community.graphs import Neo4jGraph
completion = client.completions.create(model="gpt-4",prompt="<prompt>")
from neo4j import GraphDatabase
# credential = ChainedTokenCredential(ManagedIdentityCredential(),AzureCliCredential())
# llm = AzureOpenAI()
# llm.invoke("four plus four?")


import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
from sklearn import metrics
from collections import defaultdict
import kotoba.knowledge_structure as k_s
import kotoba.chatbot_utils as c_t
import importlib
import networkx as nx
# import nxneo4j as nx
from graphdatascience import GraphDataScience
from langchain.chains import GraphCypherQAChain
from langchain_openai import ChatOpenAI


llm = c_t.get_llm()
import os
chain = GraphCypherQAChain.from_llm(graph=graph, llm=llm, verbose=True)
from openai import AzureOpenAI
response = chain.invoke({"query": "What was the cast of the Casino?"})
endpoint = os.getenv("ENDPOINT_URL", "https://dsg-genai-playground-openai-eastus.openai.azure.com/")
deployment = os.getenv("DEPLOYMENT_NAME", "dsg-gpt-4-eastus")
client = AzureOpenAI(azure_endpoint=endpoint,api_key=os.getenv("AZURE_OPENAI_API_KEY"),api_version="2024-05-01-preview")
completion = client.chat.completions.create(model=deployment
                                            , messages= [{"role": "system","content": "You are an AI assistant that helps people find information."},{"role": "user","content": "4+4?"}],
                                            max_tokens=800, temperature=0.7, top_p=0.95, frequency_penalty=0, presence_penalty=0, stop=None, stream=False)
print(completion.to_json())


fUrl = "https://www.olympus-ims.com/en/rvi-products/iplex-nx/#!cms[focus]=cmsContent13653"
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", os.environ['NEO4J_PASS']))
graph = Neo4jGraph("bolt://localhost:7687", "neo4j", os.environ['NEO4J_PASS'])
gds = GraphDataScience("bolt://localhost:7687", auth=("neo4j", os.environ['NEO4J_PASS']))


def neo4j_node(driver,G):
    nodeL = G.nodes
    nodeType = "Section {name: STRING, id: STRING}"
    queryS = "CREATE IF NOT EXISTS\n"
    for n in nodeL:
        g = G.nodes[n]
        sectS = ""
        for i in ['Chapter','Section','Subsection']:
            try:
                sectS += "%s: %s | " % (i,g[i])
            except:
                pass
               
        s = '(sum_' + str(n) + ': Section {name :"' + sectS + '"}),' + "\n"
        queryS += s
    queryS = queryS[:-2]
    driver.execute_query(queryS)
    gds.run_cypher(queryS)


def neo4j_edge(driver,G):
    #n = G.edges[(k,h)]
    edgeL = G.edges
    for e in edgeL:
        edge = edgeL[e]
    #'MATCH ('+str(k)+':Instruction {name: 'Charlie Sheen'}), (oliver:Person {name: 'Oliver Stone'})'
    driver.execute_query('('+str(k)+')-[r:CONTAINS '+str(n)+']->('+str(h)')')
   
def neo4j_graph(driver,collN):
    driver.execute_query("CREATE OR REPLACE DATABASE " + collN )


from promptflow.core import AzureOpenAIModelConfiguration
configuration = AzureOpenAIModelConfiguration(api_key=os.getenv("AZURE_OPENAI_API_KEY"),api_version=os.getenv("AZURE_OPENAI_API_VERSION"),azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),azure_deployment="")


   


gds.run_cypher("""
from promptflow.evals.evaluators
  CREATE
import ContentSafetyEvaluator, RelevanceEvaluator, CoherenceEvaluator, GroundednessEvaluator, FluencyEvaluator, SimilarityEvaluator
    (m: City {name: "Malmö"}),
content_safety_evaluator = ContentSafetyEvaluator(project_scope=azure_ai_project)
    (l: City {name: "London"}),
relevance_evaluator = RelevanceEvaluator(model_config=configuration)
    (s: City {name: "San Mateo"}),
coherence_evaluator = CoherenceEvaluator(model_config=configuration)
    (m)-[:FLY_TO]->(l),
groundedness_evaluator = GroundednessEvaluator(model_config=configuration)
    (l)-[:FLY_TO]->(m),
fluency_evaluator = FluencyEvaluator(model_config=configuration)
    (l)-[:FLY_TO]->(s),
similarity_evaluator = SimilarityEvaluator(model_config=configuration)
    (s)-[:FLY_TO]->(l)
  """)
res = gds.graph.project.estimate(["City"],"FLY_TO",readConcurrency=4)
G, result = gds.graph.project("offices",["City"],"FLY_TO",readConcurrency=4)
G = gds.graph.get("offices")
G.drop()
query = """MATCH (n)-->(m)
    RETURN gds.graph.project($graph_name, n, m, {sourceNodeLabels: $label,targetNodeLabels: $label,relationshipType: $rel_type})"""
G, result = gds.graph.cypher.project(query,database="neo4j",graph_name="offices",label="City",rel_type="FLY_TO")
n = G.node_count()
props = G.node_properties("City")
result = gds.degree.mutate(G, mutateProperty="degree")


nodeL = pd.read_csv(os.environ['HOME'] + '/lav/soft/raw/got-s1-nodes.csv')
edgeL = pd.read_csv(os.environ['HOME'] + '/lav/soft/raw/got-s1-edges.csv')


from app_target import ModelEndpoints
import pathlib
import random
from promptflow.evals.evaluate import evaluate
models = ["gpt4-0613", "gpt35-turbo", "mistral7b", "phi3_mini_serverless" ]
path = str(pathlib.Path(pathlib.Path.cwd())) + "/data.jsonl"
for model in models:
    randomNum = random.randint(1111, 9999)
    results = evaluate(
        azure_ai_project=azure_ai_project,
        evaluation_name="Eval-Run-"+str(randomNum)+"-"+model.title(),
        data=path,
        target=ModelEndpoints(env_var, model),
        evaluators={
            "content_safety": content_safety_evaluator,
            "coherence": coherence_evaluator,
            "relevance": relevance_evaluator,
            "groundedness": groundedness_evaluator,
            "fluency": fluency_evaluator,
            "similarity": similarity_evaluator,
        },
        evaluator_config={
            "content_safety": {
                "question": "${data.question}",
                "answer": "${target.answer}" 
            },
            "coherence": {
                "answer": "${target.answer}",
                "question": "${data.question}" 
            },
            "relevance": {
                "answer": "${target.answer}",
                "context": "${data.context}",
                "question": "${data.question}" 
            },
            "groundedness": {
                "answer": "${target.answer}",
                "context": "${data.context}",
                "question": "${data.question}" 
            },
            "fluency": {
                "answer": "${target.answer}",
                "context": "${data.context}",
                "question": "${data.question}" 
            },
            "similarity": {
                "answer": "${target.answer}",
                "context": "${data.context}",
                "question": "${data.question}" 
            }
        }
    )


def pd2ndeo(nodeL=None,linkL=None):
    if nodeL == None:
        nodeL = pd.DataFrame({"nodeId": [0, 1, 2, 3],"labels":  ["A", "B", "C", "A"],"prop1": [42, 1337, 8, 0],"otherProperty": [0.1, 0.2, 0.3, 0.4]})
    if linkL == None:
        linkL = pd.DataFrame({"sourceNodeId": [0, 1, 2, 3],"targetNodeId": [1, 2, 3, 0],"relationshipType": ["REL", "REL", "REL", "REL"],"weight": [0.0, 0.0, 0.1, 42.0]})
    G = gds.graph.construct("grid",nodeL,linkL)
    return G




def netx2neo(nx_G = None):
    if nx_G == None:
        nx_G = nx.DiGraph()
        nx_G.add_node(1, labels=["Person"], age=52)
        nx_G.add_node(42, labels=["Product", "Item"], cost=17.2)
        nx_G.add_edge(1, 42, relationshipType="BUYS", quantity=4)
    G = gds.graph.networkx.load(nx_G, "purchases")
    return G




importlib.reload(c_t)
input_text = "Please recommend books with a theme similar to the movie 'Inception'."
def build_document_graph(summL,collN,baseDir):
native_request = {"inputText": input_text}
    from collections import defaultdict
request = json.dumps(native_request)
    def tree(): return defaultdict(tree)
response = client.invoke_model(modelId=model_id, body=request)
    sL = ['Chapter', 'Section', 'Subsection','id']
model_response = json.loads(response["body"].read())
    treeD = tree()
print(model_response)
    for i in summL:
model_id = "anthropic.claude-3-haiku-20240307-v1:0"
        d = dict(i.metadata)
user_message = "Describe the purpose of a 'hello world' program in one line."
        for s in sL:
conversation = [{"role": "user","content": [{"text": user_message}],}]
            if s not in d:
response = client.converse(modelId=model_id,messages=conversation,inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},)
                d[s] = ''
response_text = response["output"]["message"]["content"][0]["text"]
        m = {"page_content":i.page_content,"metadata":i.metadata}
print(response_text)
        treeD[d[sL[0]]][d[sL[1]]][d[sL[2]]] = m
   
    G = nx.DiGraph(name="document_graph")
    # G = nx.DiGraph(driver)
    G.add_node(0,type="document")
    for k1 in treeD.keys():
        G.add_node(k1,type=sL[0])
        for k2 in treeD[k1].keys():
            G.add_node(k2,type=sL[1])
            G.add_edge(k1,k2)
            for k3 in treeD[k1][k2].keys():
                G.add_node(k3,type=sL[2],text=treeD[k1][k2][k3]['page_content'])
                G.add_edge(k2,k3)
       
    if False:
        #nx.draw_kamada_kawai(G,with_labels = True)
        nx.draw_spring(G,with_labels = True)
        plt.show()
    nx.write_graphml(G,baseDir + collN + ".graphml")
    nx.pagerank(G)
    nx.betweenness_centrality(G)
    nx.closeness_centrality(G)


    some_dict = {'a': 1, 'b': 2}
def load_data_to_query(question, data):
    session = driver.session()
        return str(question) + ' Answer question based on following data: ' + str(data)
    session.run(query="CREATE (x) SET x = {dict_param}",parameters={'dict_param': some_dict})


def build_knowledge_graph(summL,collN,baseDir):
def read_message(message):
    embdL = c_t.embed_text(summL)
         return message.content
    kmeans = KMeans(init="random",n_clusters=15,n_init=10,max_iter=300,random_state=42)
    kmeans.fit(embdL)
    clustL = kmeans.labels_
    treeD = defaultdict(list)
    for i,j in enumerate(clustL):
         treeD[j].append(summL[i])


    print([len(treeD[x]) for x in treeD.keys()])
def lit_eval(text):
    treeL = []
try:
    G = nx.DiGraph(name="knowledge_graph")
return literal_eval(text)
    # G = nx.DiGraph(driver)
except SyntaxError:
    G.add_node("0",name="document",id="0",Chapter=collN)
return text
    for k in treeD.keys():
        treeL.append("\n".join([x.page_content for x in treeD[k]]))
        G.add_node(k,**x.metadata)
        G.add_edge('0',k)
        for x in treeD[k]:
            i = x.metadata['id']
            G.add_node(i,**x.metadata)
            G.add_edge(k,i)


    if False:
def extract_dict(dictionary):
        nx.draw_kamada_kawai(G,with_labels = True)
return dictionary['extraction']
        plt.show()
    nx.write_graphml(G,baseDir + collN + ".graphml")
    nx.pagerank(G)
    nx.betweenness_centrality(G)
    nx.closeness_centrality(G)


def extract_dictionary(message):
    text = message.content
    open_braces = 0
    in_dict = False
    start_index = 0


if False: #categorical metrics
    for i, char in enumerate(text):
    scores = defaultdict(list)
        if char == '{':
    scores["Homogeneity"].append(metrics.homogeneity_score(labels, kmeans.labels_))
            if not in_dict:
    scores["Completeness"].append(metrics.completeness_score(labels, kmeans.labels_))
                start_index = i
    scores["V-measure"].append(metrics.v_measure_score(labels, kmeans.labels_))
                in_dict = True
    scores["Adjusted Rand-Index"].append(metrics.adjusted_rand_score(labels, km.labels_))
                open_braces += 1
     scores["Silhouette Coefficient"].append(metrics.silhouette_score(X, km.labels_, sample_size=2000))
        elif char == '}':
            open_braces -= 1
            if in_dict and open_braces == 0:
                dict_string = text[start_index:i + 1]
                try:
                    return literal_eval(dict_string)
                except ValueError as e:
                    print(f"Error parsing dictionary: {e}")
                    return None
        print("No dictionary found in the string.")
     return None


def get_table_from_test_set(image_file) -> str:
        table_path = ocr('images', 'images', image_file)
        loader = UnstructuredExcelLoader(table_path, mode="elements")
        docs = loader.load()
        return docs[0]


def get_table_from_test_set_by_table_id(table_id: str) -> str:
    table_path = ocr('images', f"./test_png/{table_id}.png")
    loader = UnstructuredExcelLoader(table_path, mode="elements")
    docs = loader.load()
    return docs[0]


def process_question(self, question, image_file):
    table = get_table_from_test_set(image_file)
    output = chain_main.invoke({"question": question, "table": table})
    # _memory.save_context({"human_input": question},{"context": output})
    return output


# Import movie information
def route(self, info):
    if "simple" in str(info["question_type"]):
        return chain_simple_extraction
    else:
        return chain_complex


movies_query = """
LOAD CSV WITH HEADERS FROM
'https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/movies/movies_small.csv'
AS row
MERGE (m:Movie {id:row.movieId})
SET m.released = date(row.released),
    m.title = row.title,
    m.imdbRating = toFloat(row.imdbRating)
FOREACH (director in split(row.director, '|') |
    MERGE (p:Person {name:trim(director)})
    MERGE (p)-[:DIRECTED]->(m))
FOREACH (actor in split(row.actors, '|') |
    MERGE (p:Person {name:trim(actor)})
    MERGE (p)-[:ACTED_IN]->(m))
FOREACH (genre in split(row.genres, '|') |
    MERGE (g:Genre {name:trim(genre)})
    MERGE (m)-[:IN_GENRE]->(g))
"""


graph.query(movies_query)


boto3_session = boto3.Session(region_name='us-east-1')
bedrock_runtime = boto3_session.client(service_name="bedrock-runtime")
llm = ChatBedrock(client=bedrock_runtime,model_id="anthropic.claude-3-sonnet-20240229-v1:0",
            model_kwargs={'temperature': 0},streaming=True,)
python_repl = PythonREPL()
repl_tool = Tool(name="python_repl",
                description="A Python shell. Use this to execute python commands. "
                "Input should be a valid python command. If you want to see the output "
                "of a value, you should print it out with `print(...)`.",
                func=python_repl.run,
                )
tools = [repl_tool]
agent = create_react_agent(llm, tools, agent_prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
chain_simple_extraction = ({"question": itemgetter("question"), "table": itemgetter("table")}
                          | simple_extraction_prompt | llm | RunnableLambda(read_message) | lit_eval)


with open(baseDir + fName + '.html') as fByte:
chain_complex_extraction = ({"decomp_dict": itemgetter("decomp_dict") | RunnableLambda(extract_dict),
    fString = fByte.read()
                            "table": itemgetter("table")}
response = requests.get(fUrl)  
                            | complex_extraction_prompt | llm | RunnableLambda(read_message))
soup = BeautifulSoup(response.text, "html.parser")
paragraphs = soup.find_all("p")
text = " ".join([p.get_text() for p in paragraphs])


user_input = "spark"
chain_simple_or_complex = ({"question": itemgetter("question"), "table": itemgetter("table")}
openai.api_key = os.environ['OPENAI_API_KEY']
                          | simple_or_complex_prompt | llm | RunnableLambda(read_message))
prompt = f"Help me understand following by describing as a detailed knowledge graph: {user_input}"
completion: KnowledgeGraph = openai.ChatCompletion.create(model="gpt-3.5-turbo-16k",messages=[{"role": "user","content": prompt,}],response_model=KnowledgeGraph,)
response_data = completion.model_dump()
edges = response_data["edges"]
def _restore(e):
    e["from"] = e["from_"]
    return e


response_data["edges"] = [_restore(e) for e in edges]
chain_decompose = ({"question": itemgetter("question")} | decomp_prompt | llm | extract_dictionary)
results = driver.get_response_data(response_data)


dot = Digraph(comment="Knowledge Graph")
chain_complex = (RunnablePassthrough.assign(decomp_dict=chain_decompose)
response_dict = response_data
                              | RunnablePassthrough.assign(data=chain_complex_extraction)
for node in response_dict.get("nodes", []):
                              | RunnablePassthrough.assign(query=lambda x: load_data_to_query(x["question"], x['data']))
    dot.node(node["id"], f"{node['label']} ({node['type']})")
                              | {"input": itemgetter("query")}
                              | (RunnablePassthrough.assign(response=agent_executor)))


for edge in response_dict.get("edges", []):
    dot.edge(edge["from"], edge["to"], label=edge["relationship"])


dot.render("knowledge_graph.gv", view=False)
qa_agent = QuestionAnsweringAgent()
dot.format = "png"
output = qa_agent.process_question(question=question, image_file=image)
dot.render("static/knowledge_graph", view=False)
png_url = f"{request.url_root}static/knowledge_graph.png"
 
(nodes, edges) = driver.get_graph_data()
response_dict = response_data
nodes = [
    {
        "data": {
            "id": node["id"],
            "label": node["label"],
            "color": node.get("color", "defaultColor"),
        }
    }
    for node in response_dict["nodes"]
]
edges = [
    {
        "data": {
            "source": edge["from"],
            "target": edge["to"],
            "label": edge["relationship"],
            "color": edge.get("color", "defaultColor"),
        }
    }
    for edge in response_dict["edges"]
]
graphD = jsonify({"elements": {"nodes": nodes, "edges": edges}})

Revision as of 12:05, 6 November 2024

import os, io, sys, re, json, base64 import boto3 from ast import literal_eval from operator import itemgetter from langchain.agents import AgentExecutor, create_react_agent from langchain_experimental.utilities import PythonREPL from langchain.agents import Tool from langchain_aws import ChatBedrock

  1. from langchain_community.chat_models import BedrockChat

from operator import itemgetter from langchain_core.runnables import RunnableLambda, RunnablePassthrough from langchain.agents import AgentExecutor, create_react_agent from langchain_experimental.utilities import PythonREPL from langchain.agents import Tool from langchain_aws import ChatBedrock

  1. from src.backend.llm.prompts import simple_extraction_prompt, complex_extraction_prompt, simple_or_complex_prompt, decomp_prompt, agent_prompt

from langchain_community.document_loaders import UnstructuredExcelLoader from azure.identity import DefaultAzureCredential

  1. os.environ["OPENAI_API_TYPE"] = "azure_ad"
  2. os.environ["OPENAI_API_KEY"] = credential.get_token("https://cognitiveservices.azure.com/.default").token

from azure.identity import ChainedTokenCredential, ManagedIdentityCredential, AzureCliCredential from langchain_openai import AzureOpenAI from openai import AzureOpenAI import openai client = AzureOpenAI(api_key=os.getenv("AZURE_OPENAI_API_KEY"),api_version=os.getenv("AZURE_OPENAI_API_VERSION"),azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT")) client = AzureOpenAI(api_key=os.getenv("AZURE_OPENAI_API_KEY"),api_version="2024-05-01-preview",azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT")) completion = client.completions.create(model="gpt-4",prompt="<prompt>")

  1. credential = ChainedTokenCredential(ManagedIdentityCredential(),AzureCliCredential())
  2. llm = AzureOpenAI()
  3. llm.invoke("four plus four?")


import os from openai import AzureOpenAI endpoint = os.getenv("ENDPOINT_URL", "https://dsg-genai-playground-openai-eastus.openai.azure.com/") deployment = os.getenv("DEPLOYMENT_NAME", "dsg-gpt-4-eastus") client = AzureOpenAI(azure_endpoint=endpoint,api_key=os.getenv("AZURE_OPENAI_API_KEY"),api_version="2024-05-01-preview") completion = client.chat.completions.create(model=deployment

                                           , messages= [{"role": "system","content": "You are an AI assistant that helps people find information."},{"role": "user","content": "4+4?"}],
                                           max_tokens=800, temperature=0.7, top_p=0.95, frequency_penalty=0, presence_penalty=0, stop=None, stream=False)

print(completion.to_json())



from promptflow.core import AzureOpenAIModelConfiguration configuration = AzureOpenAIModelConfiguration(api_key=os.getenv("AZURE_OPENAI_API_KEY"),api_version=os.getenv("AZURE_OPENAI_API_VERSION"),azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),azure_deployment="")


from promptflow.evals.evaluators import ContentSafetyEvaluator, RelevanceEvaluator, CoherenceEvaluator, GroundednessEvaluator, FluencyEvaluator, SimilarityEvaluator content_safety_evaluator = ContentSafetyEvaluator(project_scope=azure_ai_project) relevance_evaluator = RelevanceEvaluator(model_config=configuration) coherence_evaluator = CoherenceEvaluator(model_config=configuration) groundedness_evaluator = GroundednessEvaluator(model_config=configuration) fluency_evaluator = FluencyEvaluator(model_config=configuration) similarity_evaluator = SimilarityEvaluator(model_config=configuration)


from app_target import ModelEndpoints import pathlib import random from promptflow.evals.evaluate import evaluate models = ["gpt4-0613", "gpt35-turbo", "mistral7b", "phi3_mini_serverless" ] path = str(pathlib.Path(pathlib.Path.cwd())) + "/data.jsonl" for model in models:

   randomNum = random.randint(1111, 9999)
   results = evaluate(
       azure_ai_project=azure_ai_project, 
       evaluation_name="Eval-Run-"+str(randomNum)+"-"+model.title(), 
       data=path, 
       target=ModelEndpoints(env_var, model), 
       evaluators={ 
           "content_safety": content_safety_evaluator, 
           "coherence": coherence_evaluator, 
           "relevance": relevance_evaluator,
           "groundedness": groundedness_evaluator,
           "fluency": fluency_evaluator,
           "similarity": similarity_evaluator,
       }, 
       evaluator_config={ 
           "content_safety": { 
               "question": "${data.question}", 
               "answer": "${target.answer}"  
           }, 
           "coherence": { 
               "answer": "${target.answer}", 
               "question": "${data.question}"  
           }, 
           "relevance": { 
               "answer": "${target.answer}", 
               "context": "${data.context}", 
               "question": "${data.question}"  
           }, 
           "groundedness": { 
               "answer": "${target.answer}", 
               "context": "${data.context}", 
               "question": "${data.question}"  
           }, 
           "fluency": { 
               "answer": "${target.answer}", 
               "context": "${data.context}", 
               "question": "${data.question}"  
           }, 
           "similarity": { 
               "answer": "${target.answer}", 
               "context": "${data.context}", 
               "question": "${data.question}"  
           } 
       } 
   )



input_text = "Please recommend books with a theme similar to the movie 'Inception'." native_request = {"inputText": input_text} request = json.dumps(native_request) response = client.invoke_model(modelId=model_id, body=request) model_response = json.loads(response["body"].read()) print(model_response) model_id = "anthropic.claude-3-haiku-20240307-v1:0" user_message = "Describe the purpose of a 'hello world' program in one line." conversation = [{"role": "user","content": [{"text": user_message}],}] response = client.converse(modelId=model_id,messages=conversation,inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},) response_text = response["output"]["message"]["content"][0]["text"] print(response_text)

def load_data_to_query(question, data):

       return str(question) + ' Answer question based on following data: ' + str(data)

def read_message(message):

       return message.content

def lit_eval(text): try: return literal_eval(text) except SyntaxError: return text

def extract_dict(dictionary): return dictionary['extraction']

def extract_dictionary(message):

   text = message.content
   open_braces = 0
   in_dict = False
   start_index = 0
   for i, char in enumerate(text):
       if char == '{':
           if not in_dict:
               start_index = i
               in_dict = True
               open_braces += 1
       elif char == '}':
           open_braces -= 1
           if in_dict and open_braces == 0:
               dict_string = text[start_index:i + 1]
               try:
                   return literal_eval(dict_string)
               except ValueError as e:
                   print(f"Error parsing dictionary: {e}")
                   return None
       print("No dictionary found in the string.")
   return None

def get_table_from_test_set(image_file) -> str:

       table_path = ocr('images', 'images', image_file)
       loader = UnstructuredExcelLoader(table_path, mode="elements")
       docs = loader.load()
       return docs[0]

def get_table_from_test_set_by_table_id(table_id: str) -> str:

   table_path = ocr('images', f"./test_png/{table_id}.png")
   loader = UnstructuredExcelLoader(table_path, mode="elements")
   docs = loader.load()
   return docs[0]

def process_question(self, question, image_file):

   table = get_table_from_test_set(image_file)
   output = chain_main.invoke({"question": question, "table": table})
   # _memory.save_context({"human_input": question},{"context": output})
   return output

def route(self, info):

   if "simple" in str(info["question_type"]):
       return chain_simple_extraction
   else:
       return chain_complex


boto3_session = boto3.Session(region_name='us-east-1') bedrock_runtime = boto3_session.client(service_name="bedrock-runtime") llm = ChatBedrock(client=bedrock_runtime,model_id="anthropic.claude-3-sonnet-20240229-v1:0",

           model_kwargs={'temperature': 0},streaming=True,)

python_repl = PythonREPL() repl_tool = Tool(name="python_repl",

                description="A Python shell. Use this to execute python commands. "
                "Input should be a valid python command. If you want to see the output "
                "of a value, you should print it out with `print(...)`.",
                func=python_repl.run,
                )

tools = [repl_tool] agent = create_react_agent(llm, tools, agent_prompt) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) chain_simple_extraction = ({"question": itemgetter("question"), "table": itemgetter("table")}

                          | simple_extraction_prompt | llm | RunnableLambda(read_message) | lit_eval)

chain_complex_extraction = ({"decomp_dict": itemgetter("decomp_dict") | RunnableLambda(extract_dict),

                            "table": itemgetter("table")}
                           | complex_extraction_prompt | llm | RunnableLambda(read_message))

chain_simple_or_complex = ({"question": itemgetter("question"), "table": itemgetter("table")}

                          | simple_or_complex_prompt | llm | RunnableLambda(read_message))

chain_decompose = ({"question": itemgetter("question")} | decomp_prompt | llm | extract_dictionary)

chain_complex = (RunnablePassthrough.assign(decomp_dict=chain_decompose)

                             | RunnablePassthrough.assign(data=chain_complex_extraction)
                             | RunnablePassthrough.assign(query=lambda x: load_data_to_query(x["question"], x['data']))
                             | {"input": itemgetter("query")}
                             | (RunnablePassthrough.assign(response=agent_executor)))


qa_agent = QuestionAnsweringAgent() output = qa_agent.process_question(question=question, image_file=image)