prompt
stringlengths
70
19.8k
completion
stringlengths
8
303
api
stringlengths
23
93
get_ipython().run_line_magic('pip', 'install llama-index-readers-pinecone') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) api_key = "<api_key>" get_ipython().system('pip install llama-index') from llama_index.readers.pinecone import PineconeReader reader =
PineconeReader(api_key=api_key, environment="us-west1-gcp")
llama_index.readers.pinecone.PineconeReader
import openai openai.api_key = "sk-your-key" from llama_index.agent import OpenAIAgent from llama_index.tools.gmail.base import GmailToolSpec tool_spec =
GmailToolSpec()
llama_index.tools.gmail.base.GmailToolSpec
get_ipython().run_line_magic('pip', 'install llama-index-question-gen-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') from IPython.display import Markdown, display def display_prompt_dict(prompts_dict): for k, p in prompts_dict.items(): text_md = f"**Prompt Key**: {k}<br>" f"**Text:** <br>" display(Markdown(text_md)) print(p.get_template()) display(Markdown("<br><br>")) from llama_index.core.selectors import LLMSingleSelector, LLMMultiSelector from llama_index.core.selectors import ( PydanticMultiSelector, PydanticSingleSelector, ) selector = LLMMultiSelector.from_defaults() from llama_index.core.tools import ToolMetadata tool_choices = [ ToolMetadata( name="covid_nyt", description=("This tool contains a NYT news article about COVID-19"), ), ToolMetadata( name="covid_wiki", description=("This tool contains the Wikipedia page about COVID-19"), ), ToolMetadata( name="covid_tesla", description=("This tool contains the Wikipedia page about apples"), ), ] display_prompt_dict(selector.get_prompts()) selector_result = selector.select( tool_choices, query="Tell me more about COVID-19" ) selector_result.selections from llama_index.core import PromptTemplate from llama_index.llms.openai import OpenAI query_gen_str = """\ You are a helpful assistant that generates multiple search queries based on a \ single input query. Generate {num_queries} search queries, one on each line, \ related to the following input query: Query: {query} Queries: """ query_gen_prompt = PromptTemplate(query_gen_str) llm = OpenAI(model="gpt-3.5-turbo") def generate_queries(query: str, llm, num_queries: int = 4): response = llm.predict( query_gen_prompt, num_queries=num_queries, query=query ) queries = response.split("\n") queries_str = "\n".join(queries) print(f"Generated queries:\n{queries_str}") return queries queries = generate_queries("What happened at Interleaf and Viaweb?", llm) queries from llama_index.core.indices.query.query_transform import HyDEQueryTransform from llama_index.llms.openai import OpenAI hyde = HyDEQueryTransform(include_original=True) llm = OpenAI(model="gpt-3.5-turbo") query_bundle = hyde.run("What is Bel?") new_query.custom_embedding_strs from llama_index.core.question_gen import LLMQuestionGenerator from llama_index.question_gen.openai import OpenAIQuestionGenerator from llama_index.llms.openai import OpenAI llm = OpenAI() question_gen = OpenAIQuestionGenerator.from_defaults(llm=llm) display_prompt_dict(question_gen.get_prompts()) from llama_index.core.tools import ToolMetadata tool_choices = [ ToolMetadata( name="uber_2021_10k", description=( "Provides information about Uber financials for year 2021" ), ), ToolMetadata( name="lyft_2021_10k", description=( "Provides information about Lyft financials for year 2021" ), ), ] from llama_index.core import QueryBundle query_str = "Compare and contrast Uber and Lyft" choices = question_gen.generate(tool_choices,
QueryBundle(query_str=query_str)
llama_index.core.QueryBundle
get_ipython().run_line_magic('pip', 'install llama-index-multi-modal-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-qdrant') get_ipython().run_line_magic('pip', 'install llama_index ftfy regex tqdm') get_ipython().run_line_magic('pip', 'install git+https://github.com/openai/CLIP.git') get_ipython().run_line_magic('pip', 'install torch torchvision') get_ipython().run_line_magic('pip', 'install matplotlib scikit-image') get_ipython().run_line_magic('pip', 'install -U qdrant_client') import os OPENAI_API_TOKEN = "sk-" os.environ["OPENAI_API_KEY"] = OPENAI_API_TOKEN import wikipedia import urllib.request from pathlib import Path image_path = Path("mixed_wiki") image_uuid = 0 image_metadata_dict = {} MAX_IMAGES_PER_WIKI = 30 wiki_titles = [ "Vincent van Gogh", "San Francisco", "Batman", "iPhone", "Tesla Model S", "BTS band", ] if not image_path.exists(): Path.mkdir(image_path) for title in wiki_titles: images_per_wiki = 0 print(title) try: page_py = wikipedia.page(title) list_img_urls = page_py.images for url in list_img_urls: if url.endswith(".jpg") or url.endswith(".png"): image_uuid += 1 image_file_name = title + "_" + url.split("/")[-1] image_metadata_dict[image_uuid] = { "filename": image_file_name, "img_path": "./" + str(image_path / f"{image_uuid}.jpg"), } urllib.request.urlretrieve( url, image_path / f"{image_uuid}.jpg" ) images_per_wiki += 1 if images_per_wiki > MAX_IMAGES_PER_WIKI: break except: print(str(Exception("No images found for Wikipedia page: ")) + title) continue from PIL import Image import matplotlib.pyplot as plt import os image_paths = [] for img_path in os.listdir("./mixed_wiki"): image_paths.append(str(os.path.join("./mixed_wiki", img_path))) def plot_images(image_paths): images_shown = 0 plt.figure(figsize=(16, 9)) for img_path in image_paths: if os.path.isfile(img_path): image = Image.open(img_path) plt.subplot(3, 3, images_shown + 1) plt.imshow(image) plt.xticks([]) plt.yticks([]) images_shown += 1 if images_shown >= 9: break plot_images(image_paths) from llama_index.core.indices import MultiModalVectorStoreIndex from llama_index.vector_stores.qdrant import QdrantVectorStore from llama_index.core import SimpleDirectoryReader, StorageContext import qdrant_client from llama_index.core import SimpleDirectoryReader client = qdrant_client.QdrantClient(path="qdrant_img_db") text_store = QdrantVectorStore( client=client, collection_name="text_collection" ) image_store = QdrantVectorStore( client=client, collection_name="image_collection" ) storage_context = StorageContext.from_defaults( vector_store=text_store, image_store=image_store ) documents = SimpleDirectoryReader("./mixed_wiki/").load_data() index = MultiModalVectorStoreIndex.from_documents( documents, storage_context=storage_context, ) input_image = "./mixed_wiki/2.jpg" plot_images([input_image]) retriever_engine = index.as_retriever(image_similarity_top_k=4) retrieval_results = retriever_engine.image_to_image_retrieve( "./mixed_wiki/2.jpg" ) retrieved_images = [] for res in retrieval_results: retrieved_images.append(res.node.metadata["file_path"]) plot_images(retrieved_images[1:]) from llama_index.multi_modal_llms.openai import OpenAIMultiModal from llama_index.core import SimpleDirectoryReader from llama_index.core.schema import ImageDocument image_documents = [ImageDocument(image_path=input_image)] for res_img in retrieved_images[1:]: image_documents.append(ImageDocument(image_path=res_img)) openai_mm_llm = OpenAIMultiModal( model="gpt-4-vision-preview", api_key=OPENAI_API_TOKEN, max_new_tokens=1500 ) response = openai_mm_llm.complete( prompt="Given the first image as the base image, what the other images correspond to?", image_documents=image_documents, ) print(response) from llama_index.multi_modal_llms.openai import OpenAIMultiModal from llama_index.core import PromptTemplate qa_tmpl_str = ( "Given the images provided, " "answer the query.\n" "Query: {query_str}\n" "Answer: " ) qa_tmpl =
PromptTemplate(qa_tmpl_str)
llama_index.core.PromptTemplate
get_ipython().run_line_magic('pip', 'install llama-index-program-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-llama-api') get_ipython().system('pip install llama-index') from llama_index.llms.llama_api import LlamaAPI api_key = "LL-your-key" llm = LlamaAPI(api_key=api_key) resp = llm.complete("Paul Graham is ") print(resp) from llama_index.core.llms import ChatMessage messages = [ ChatMessage( role="system", content="You are a pirate with a colorful personality" ), ChatMessage(role="user", content="What is your name"), ] resp = llm.chat(messages) print(resp) from pydantic import BaseModel from llama_index.core.llms.openai_utils import to_openai_function class Song(BaseModel): """A song with name and artist""" name: str artist: str song_fn = to_openai_function(Song) llm =
LlamaAPI(api_key=api_key)
llama_index.llms.llama_api.LlamaAPI
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-docarray') get_ipython().system('pip install llama-index') import os import sys import logging import textwrap import warnings warnings.filterwarnings("ignore") os.environ["TOKENIZERS_PARALLELISM"] = "false" from llama_index.core import ( GPTVectorStoreIndex, SimpleDirectoryReader, Document, ) from llama_index.vector_stores.docarray import DocArrayHnswVectorStore from IPython.display import Markdown, display import os os.environ["OPENAI_API_KEY"] = "<your openai key>" get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") documents = SimpleDirectoryReader("./data/paul_graham/").load_data() print( "Document ID:", documents[0].doc_id, "Document Hash:", documents[0].doc_hash, ) from llama_index.core import StorageContext vector_store =
DocArrayHnswVectorStore(work_dir="hnsw_index")
llama_index.vector_stores.docarray.DocArrayHnswVectorStore
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-tencentvectordb') get_ipython().system('pip install llama-index') get_ipython().system('pip install tcvectordb') from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, StorageContext, ) from llama_index.vector_stores.tencentvectordb import TencentVectorDB from llama_index.core.vector_stores.tencentvectordb import ( CollectionParams, FilterField, ) import tcvectordb tcvectordb.debug.DebugEnable = False import openai OPENAI_API_KEY = getpass.getpass("OpenAI API Key:") openai.api_key = OPENAI_API_KEY get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") documents = SimpleDirectoryReader("./data/paul_graham").load_data() print(f"Total documents: {len(documents)}") print(f"First document, id: {documents[0].doc_id}") print(f"First document, hash: {documents[0].hash}") print( f"First document, text ({len(documents[0].text)} characters):\n{'='*20}\n{documents[0].text[:360]} ..." ) vector_store = TencentVectorDB( url="http://10.0.X.X", key="eC4bLRy2va******************************", collection_params=CollectionParams(dimension=1536, drop_exists=True), ) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex.from_documents( documents, storage_context=storage_context ) query_engine = index.as_query_engine() response = query_engine.query("Why did the author choose to work on AI?") print(response) query_engine = index.as_query_engine(vector_store_query_mode="mmr") response = query_engine.query("Why did the author choose to work on AI?") print(response) new_vector_store = TencentVectorDB( url="http://10.0.X.X", key="eC4bLRy2va******************************", collection_params=
CollectionParams(dimension=1536, drop_exists=False)
llama_index.core.vector_stores.tencentvectordb.CollectionParams
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-llms-huggingface') get_ipython().system('pip install llama-index') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core.postprocessor import ( PIINodePostprocessor, NERPIINodePostprocessor, ) from llama_index.llms.huggingface import HuggingFaceLLM from llama_index.core import Document, VectorStoreIndex from llama_index.core.schema import TextNode text = """ Hello Paulo Santos. The latest statement for your credit card account \ 1111-0000-1111-0000 was mailed to 123 Any Street, Seattle, WA 98109. """ node = TextNode(text=text) processor = NERPIINodePostprocessor() from llama_index.core.schema import NodeWithScore new_nodes = processor.postprocess_nodes([NodeWithScore(node=node)]) new_nodes[0].node.get_text() new_nodes[0].node.metadata["__pii_node_info__"] from llama_index.llms.openai import OpenAI processor = PIINodePostprocessor(llm=OpenAI()) from llama_index.core.schema import NodeWithScore new_nodes = processor.postprocess_nodes([NodeWithScore(node=node)]) new_nodes[0].node.get_text() new_nodes[0].node.metadata["__pii_node_info__"] text = """ Hello Paulo Santos. The latest statement for your credit card account \ 4095-2609-9393-4932 was mailed to Seattle, WA 98109. \ IBAN GB90YNTU67299444055881 and social security number is 474-49-7577 were verified on the system. \ Further communications will be sent to [email protected] """ presidio_node = TextNode(text=text) from llama_index.postprocessor.presidio import PresidioPIINodePostprocessor processor =
PresidioPIINodePostprocessor()
llama_index.postprocessor.presidio.PresidioPIINodePostprocessor
import os from getpass import getpass if os.getenv("OPENAI_API_KEY") is None: os.environ["OPENAI_API_KEY"] = getpass( "Paste your OpenAI key from:" " https://platform.openai.com/account/api-keys\n" ) assert os.getenv("OPENAI_API_KEY", "").startswith( "sk-" ), "This doesn't look like a valid OpenAI API key" print("OpenAI API key configured") get_ipython().run_line_magic('pip', 'install -q html2text llama-index pandas pyarrow tqdm') get_ipython().run_line_magic('pip', 'install -q llama-index-readers-web') get_ipython().run_line_magic('pip', 'install -q llama-index-callbacks-openinference') import hashlib import json from pathlib import Path import os import textwrap from typing import List, Union import llama_index.core from llama_index.readers.web import SimpleWebPageReader from llama_index.core import VectorStoreIndex from llama_index.core.node_parser import SentenceSplitter from llama_index.core.callbacks import CallbackManager from llama_index.callbacks.openinference import OpenInferenceCallbackHandler from llama_index.callbacks.openinference.base import ( as_dataframe, QueryData, NodeData, ) from llama_index.core.node_parser import SimpleNodeParser import pandas as pd from tqdm import tqdm documents = SimpleWebPageReader().load_data( [ "https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt" ] ) print(documents[0].text) parser = SentenceSplitter() nodes = parser.get_nodes_from_documents(documents) print(nodes[0].text) callback_handler = OpenInferenceCallbackHandler() callback_manager = CallbackManager([callback_handler]) llama_index.core.Settings.callback_manager = callback_manager index = VectorStoreIndex.from_documents(documents) query_engine = index.as_query_engine() max_characters_per_line = 80 queries = [ "What did Paul Graham do growing up?", "When and how did Paul Graham's mother die?", "What, in Paul Graham's opinion, is the most distinctive thing about YC?", "When and how did Paul Graham meet Jessica Livingston?", "What is Bel, and when and where was it written?", ] for query in queries: response = query_engine.query(query) print("Query") print("=====") print(textwrap.fill(query, max_characters_per_line)) print() print("Response") print("========") print(textwrap.fill(str(response), max_characters_per_line)) print() query_data_buffer = callback_handler.flush_query_data_buffer() query_dataframe = as_dataframe(query_data_buffer) query_dataframe class ParquetCallback: def __init__( self, data_path: Union[str, Path], max_buffer_length: int = 1000 ): self._data_path = Path(data_path) self._data_path.mkdir(parents=True, exist_ok=False) self._max_buffer_length = max_buffer_length self._batch_index = 0 def __call__( self, query_data_buffer: List[QueryData], node_data_buffer: List[NodeData], ) -> None: if len(query_data_buffer) >= self._max_buffer_length: query_dataframe = as_dataframe(query_data_buffer) file_path = self._data_path / f"log-{self._batch_index}.parquet" query_dataframe.to_parquet(file_path) self._batch_index += 1 query_data_buffer.clear() # 鈿狅笍 clear the buffer or it will keep growing forever! node_data_buffer.clear() # didn't log node_data_buffer, but still need to clear it data_path = "data" parquet_writer = ParquetCallback( data_path=data_path, max_buffer_length=1, ) callback_handler =
OpenInferenceCallbackHandler(callback=parquet_writer)
llama_index.callbacks.openinference.OpenInferenceCallbackHandler
get_ipython().system('pip install llama-index') import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout)) from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, load_index_from_storage, StorageContext, ) from IPython.display import Markdown, display import dotenv import s3fs import os dotenv.load_dotenv("../../../.env") AWS_KEY = os.environ["AWS_ACCESS_KEY_ID"] AWS_SECRET = os.environ["AWS_SECRET_ACCESS_KEY"] R2_ACCOUNT_ID = os.environ["R2_ACCOUNT_ID"] assert AWS_KEY is not None and AWS_KEY != "" s3 = s3fs.S3FileSystem( key=AWS_KEY, secret=AWS_SECRET, endpoint_url=f"https://{R2_ACCOUNT_ID}.r2.cloudflarestorage.com", s3_additional_kwargs={"ACL": "public-read"}, ) get_ipython().system("mkdir -p 'data/paul_graham/'") get_ipython().system("wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'") documents = SimpleDirectoryReader("./data/paul_graham/").load_data() print(len(documents)) index = VectorStoreIndex.from_documents(documents, fs=s3) index.set_index_id("vector_index") index.storage_context.persist("llama-index/storage_demo", fs=s3) s3.listdir("llama-index/storage_demo") sc = StorageContext.from_defaults( persist_dir="llama-index/storage_demo", fs=s3 ) index2 =
load_index_from_storage(sc, "vector_index")
llama_index.core.load_index_from_storage
get_ipython().run_line_magic('pip', 'install llama-index-callbacks-wandb') get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') import os from getpass import getpass if os.getenv("OPENAI_API_KEY") is None: os.environ["OPENAI_API_KEY"] = getpass( "Paste your OpenAI key from:" " https://platform.openai.com/account/api-keys\n" ) assert os.getenv("OPENAI_API_KEY", "").startswith( "sk-" ), "This doesn't look like a valid OpenAI API key" print("OpenAI API key configured") from llama_index.core.callbacks import CallbackManager from llama_index.core.callbacks import LlamaDebugHandler from llama_index.callbacks.wandb import WandbCallbackHandler from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, SimpleKeywordTableIndex, StorageContext, ) from llama_index.llms.openai import OpenAI from llama_index.core import Settings Settings.llm = OpenAI(model="gpt-4", temperature=0) import llama_index.core from llama_index.core import set_global_handler
set_global_handler("wandb", run_args={"project": "llamaindex"})
llama_index.core.set_global_handler
get_ipython().run_line_magic('pip', 'install llama-index-vector-stores-deeplake') get_ipython().system('pip install llama-index') get_ipython().system('pip install deeplake') import os import textwrap from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Document from llama_index.vector_stores.deeplake import DeepLakeVectorStore os.environ["OPENAI_API_KEY"] = "sk-********************************" os.environ["ACTIVELOOP_TOKEN"] = "********************************" import urllib.request urllib.request.urlretrieve( "https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt", "data/paul_graham/paul_graham_essay.txt", ) documents = SimpleDirectoryReader("./data/paul_graham/").load_data() print( "Document ID:", documents[0].doc_id, "Document Hash:", documents[0].hash, ) from llama_index.core import StorageContext dataset_path = "./dataset/paul_graham" vector_store =
DeepLakeVectorStore(dataset_path=dataset_path, overwrite=True)
llama_index.vector_stores.deeplake.DeepLakeVectorStore
get_ipython().run_line_magic('pip', 'install llama-index-evaluation-tonic-validate') import json import pandas as pd from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.evaluation.tonic_validate import ( AnswerConsistencyEvaluator, AnswerSimilarityEvaluator, AugmentationAccuracyEvaluator, AugmentationPrecisionEvaluator, RetrievalPrecisionEvaluator, TonicValidateEvaluator, ) question = "What makes Sam Altman a good founder?" reference_answer = "He is smart and has a great force of will." llm_answer = "He is a good founder because he is smart." retrieved_context_list = [ "Sam Altman is a good founder. He is very smart.", "What makes Sam Altman such a good founder is his great force of will.", ] answer_similarity_evaluator = AnswerSimilarityEvaluator() score = await answer_similarity_evaluator.aevaluate( question, llm_answer, retrieved_context_list, reference_response=reference_answer, ) score answer_consistency_evaluator = AnswerConsistencyEvaluator() score = await answer_consistency_evaluator.aevaluate( question, llm_answer, retrieved_context_list ) score augmentation_accuracy_evaluator =
AugmentationAccuracyEvaluator()
llama_index.evaluation.tonic_validate.AugmentationAccuracyEvaluator
get_ipython().run_line_magic('pip', 'install llama-index-llms-openai') get_ipython().run_line_magic('pip', 'install llama-index-program-evaporate') get_ipython().system('pip install llama-index') get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') wiki_titles = ["Toronto", "Seattle", "Chicago", "Boston", "Houston"] from pathlib import Path import requests for title in wiki_titles: response = requests.get( "https://en.wikipedia.org/w/api.php", params={ "action": "query", "format": "json", "titles": title, "prop": "extracts", "explaintext": True, }, ).json() page = next(iter(response["query"]["pages"].values())) wiki_text = page["extract"] data_path = Path("data") if not data_path.exists(): Path.mkdir(data_path) with open(data_path / f"{title}.txt", "w") as fp: fp.write(wiki_text) from llama_index.core import SimpleDirectoryReader city_docs = {} for wiki_title in wiki_titles: city_docs[wiki_title] = SimpleDirectoryReader( input_files=[f"data/{wiki_title}.txt"] ).load_data() from llama_index.llms.openai import OpenAI from llama_index.core import Settings Settings.llm = OpenAI(temperature=0, model="gpt-3.5-turbo") Settings.chunk_size = 512 city_nodes = {} for wiki_title in wiki_titles: docs = city_docs[wiki_title] nodes =
Settings.node_parser.get_nodes_from_documents(docs)
llama_index.core.Settings.node_parser.get_nodes_from_documents
get_ipython().run_line_magic('pip', 'install llama-index-llms-bedrock') get_ipython().system('pip install llama-index') from llama_index.llms.bedrock import Bedrock profile_name = "Your aws profile name" resp = Bedrock( model="amazon.titan-text-express-v1", profile_name=profile_name ).complete("Paul Graham is ") print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.bedrock import Bedrock messages = [ ChatMessage( role="system", content="You are a pirate with a colorful personality" ), ChatMessage(role="user", content="Tell me a story"), ] resp = Bedrock( model="amazon.titan-text-express-v1", profile_name=profile_name ).chat(messages) print(resp) from llama_index.llms.bedrock import Bedrock llm = Bedrock(model="amazon.titan-text-express-v1", profile_name=profile_name) resp = llm.stream_complete("Paul Graham is ") for r in resp: print(r.delta, end="") from llama_index.llms.bedrock import Bedrock llm = Bedrock(model="amazon.titan-text-express-v1", profile_name=profile_name) messages = [ ChatMessage( role="system", content="You are a pirate with a colorful personality" ), ChatMessage(role="user", content="Tell me a story"), ] resp = llm.stream_chat(messages) for r in resp: print(r.delta, end="") from llama_index.llms.bedrock import Bedrock llm =
Bedrock(model="amazon.titan-text-express-v1", profile_name=profile_name)
llama_index.llms.bedrock.Bedrock
get_ipython().run_line_magic('pip', 'install llama-index-llms-watsonx') from llama_index.llms.watsonx import WatsonX credentials = { "url": "https://enter.your-ibm.url", "apikey": "insert_your_api_key", } project_id = "insert_your_project_id" resp = WatsonX(credentials=credentials, project_id=project_id).complete( "Paul Graham is" ) print(resp) from llama_index.core.llms import ChatMessage from llama_index.llms.watsonx import WatsonX messages = [ ChatMessage( role="system", content="You are a pirate with a colorful personality" ), ChatMessage(role="user", content="Tell me a story"), ] resp = WatsonX( model_id="meta-llama/llama-2-70b-chat", credentials=credentials, project_id=project_id, ).chat(messages) print(resp) from llama_index.llms.watsonx import WatsonX llm =
WatsonX(credentials=credentials, project_id=project_id)
llama_index.llms.watsonx.WatsonX