id stringlengths 14 16 | text stringlengths 45 2.73k | source stringlengths 49 114 |
|---|---|---|
5c280d14223f-4 | from langchain.embeddings import OpenAIEmbeddings
from langchain.tools.human.tool import HumanInputRun
embeddings_model = OpenAIEmbeddings()
embedding_size = 1536
index = faiss.IndexFlatL2(embedding_size)
vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})
Setup model and AutoGPT#
Model s... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
5c280d14223f-5 | "reasoning": "I'll start by conducting a web search for the requested information.",
"plan": "- Conduct a web search\n- Query relevant webpage\n- Generate table\n- Save data to file",
"criticism": "None",
"speak": "I will begin by conducting a web search to find the past 5 years' Boston Marathon... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
5c280d14223f-6 | {
"thoughts": {
"text": "I have the winning times of the Boston Marathon for the past 5 years. I need to create a table with the names, countries of origin, and times.",
"reasoning": "I can use the information I've retrieved to generate a CSV file, then process the CSV file to create the table.",
... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
5c280d14223f-7 | "plan": "- Format the data as a CSV\n- Write the CSV to disk\n- Process the CSV and generate a table",
"criticism": "None",
"speak": "I will now format the winning times data as a CSV, save it, and process it to generate a table."
},
"command": {
"name": "write_file",
"args": {
... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
5c280d14223f-8 | "args": {
"file_path": "boston_marathon_winners.csv",
"text": "Year,Name,Country,Time\n2022,Evans Chebet,Kenya,2:06:51\n2021,Benson Kipruto,Kenya,2:09:51\n2019,Lawrence Cherono,Kenya,2:07:57\n2018,Yuki Kawauchi,Japan,2:15:58\n2017,Geoffrey Kirui,Kenya,2:09:37"
}
}
}
WARNING:root:Fail... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
5c280d14223f-9 | Action: python_repl_ast
Action Input: df.to_markdown(index=False)
Observation: | Year | Name | Country | Time |
|-------:|:-----------------|:----------|:--------|
| 2022 | Evans Chebet | Kenya | 2:06:51 |
| 2021 | Benson Kipruto | Kenya | 2:09:51 |
| 2019 | Lawrence Cherono | Ken... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
5c280d14223f-10 | "reasoning": "I have completed my task on this topic, so I don't need to use any other commands.",
"plan": "- Inform the user that the task is complete",
"criticism": "None",
"speak": "I have found the winning times for the past 5 years of the Boston Marathon and created a table. My task is comp... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
7a1b59930457-0 | .ipynb
.pdf
BabyAGI User Guide
Contents
Install and Import Required Modules
Connect to the Vector Store
Run the BabyAGI
BabyAGI User Guide#
This notebook demonstrates how to implement BabyAGI by Yohei Nakajima. BabyAGI is an AI agent that can generate and pretend to execute tasks based on a given objective.
This guid... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi.html |
7a1b59930457-1 | Now it’s time to create the BabyAGI controller and watch it try to accomplish your objective.
OBJECTIVE = "Write a weather report for SF today"
llm = OpenAI(temperature=0)
# Logging of LLMChains
verbose = False
# If None, will keep on going forever
max_iterations: Optional[int] = 3
baby_agi = BabyAGI.from_llm(
llm=... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi.html |
7a1b59930457-2 | *****NEXT TASK*****
2: Check the current temperature in San Francisco
*****TASK RESULT*****
I will check the current temperature in San Francisco. I will use an online weather service to get the most up-to-date information.
*****TASK LIST*****
3: Check the current UV index in San Francisco.
4: Check the current air qua... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi.html |
aa6ea636b131-0 | .ipynb
.pdf
Generative Agents in LangChain
Contents
Generative Agent Memory Components
Memory Lifecycle
Create a Generative Character
Pre-Interview with Character
Step through the day’s observations.
Interview after the day
Adding Multiple Characters
Pre-conversation interviews
Dialogue between Generative Agents
Let’... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-1 | Observations - from dialogues or interactions with the virtual world, about self or others
Reflections - resurfaced and summarized core memories
Memory Recall
Memories are retrieved using a weighted sum of salience, recency, and importance.
Review the definition below, focusing on add_memory and summarize_related_memor... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-2 | lines = re.split(r'\n', text.strip())
return [re.sub(r'^\s*\d+\.\s*', '', line).strip() for line in lines]
def _compute_agent_summary(self):
""""""
prompt = PromptTemplate.from_template(
"How would you summarize {name}'s core characteristics given the"
+" following st... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-3 | result = reflection_chain.run(observations=observation_str)
return self._parse_list(result)
def _get_insights_on_topic(self, topic: str) -> List[str]:
"""Generate 'insights' on a topic of reflection, based on pertinent memories."""
prompt = PromptTemplate.from_template(
"Sta... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-4 | """Score the absolute importance of the given memory."""
# A weight of 0.25 makes this less important than it
# would be otherwise, relative to salience and time
prompt = PromptTemplate.from_template(
"On the scale of 1 to 10, where 1 is purely mundane"
+" (e.g., brushing teeth... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-5 | and self.memory_importance > self.reflection_threshold
and self.status != "Reflecting"):
old_status = self.status
self.status = "Reflecting"
self.pause_to_reflect()
# Hack to clear the importance from reflection
self.memory_importance = 0.0
... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-6 | prompt = PromptTemplate.from_template(
"What is the observed entity in the following observation? {observation}"
+"\nEntity="
)
chain = LLMChain(llm=self.llm, prompt=prompt, verbose=self.verbose)
return chain.run(observation=observation).strip()
def _get_entity_action... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-7 | q1 = f"What is the relationship between {self.name} and {entity_name}"
relevant_memories = self.fetch_memories(q1) # Fetch memories related to the agent's relationship with the entity
q2 = f"{entity_name} is {entity_action}"
relevant_memories += self.fetch_memories(q2) # Fetch things related to ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-8 | +"\n{relevant_memories}"
+"\nMost recent observations: {recent_observations}"
+ "\nObservation: {observation}"
+ "\n\n" + suffix
)
agent_summary_description = self.get_summary()
relevant_memories_str = self.summarize_related_memories(observation)
... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-9 | result = full_result.strip().split('\n')[0]
self.add_memory(f"{self.name} observed {observation} and reacted by {result}")
if "REACT:" in result:
reaction = result.split("REACT:")[-1].strip()
return False, f"{self.name} {reaction}"
if "SAY:" in result:
said_va... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-10 | Memory Lifecycle#
Summarizing the above key methods: add_memory and summarize_related_memories.
When an agent makes an observation, it stores the memory:
Language model scores the memory’s importance (1 for mundane, 10 for poignant)
Observation and importance are stored within a document by TimeWeightedVectorStoreRetri... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-11 | index = faiss.IndexFlatL2(embedding_size)
vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {}, relevance_score_fn=relevance_score_fn)
return TimeWeightedVectorStoreRetriever(vectorstore=vectorstore, other_score_keys=["importance"], k=15)
tommie = GenerativeAgent(name="Tommie", ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-12 | ]
for memory in tommie_memories:
tommie.add_memory(memory)
# Now that Tommie has 'memories', their self-summary is more descriptive, though still rudimentary.
# We will see how this summary updates after more observations to create a more rich description.
print(tommie.get_summary(force_refresh=True))
Name: Tommie ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-13 | interview_agent(tommie, "What are you most worried about today?")
'Tommie said "Honestly, I\'m feeling pretty anxious about finding a job. It\'s been a bit of a struggle and I\'m not sure what my next step should be. But I\'m trying to stay positive and keep pushing forward."'
Step through the day’s observations.#
# Le... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-14 | "Tommie overhears a conversation at the next table about a job opening.",
"Tommie asks the diners about the job opening and gets some information about the company.",
"Tommie decides to apply for the job and sends his resume and cover letter.",
"Tommie continues his search for job openings and drops off his... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-15 | print('*'*40)
print(colored(f"After {i+1} observations, Tommie's summary is:\n{tommie.get_summary(force_refresh=True)}", "blue"))
print('*'*40)
Tommie wakes up to the sound of a noisy construction site outside his window. Tommie Tommie groans and covers their head with a pillow, trying to block out the ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-16 | The line to get in is long, and Tommie has to wait for an hour. Tommie Tommie feels frustrated and restless while waiting in line.
Tommie meets several potential employers at the job fair but doesn't receive any offers. Tommie Tommie feels disappointed but remains determined to keep searching for job openings.
Tommie l... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-17 | ****************************************
After 20 observations, Tommie's summary is:
Name: Tommie (age: 25)
Innate traits: anxious, likes design
Tommie is a determined individual who is actively searching for job opportunities. He feels both hopeful and anxious about his search and remains positive despite facing disap... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-18 | Tommie's friend offers some words of encouragement and tells him to keep trying. Tommie said "Thank you for the encouragement, it means a lot. I'll keep trying."
Tommie feels slightly better after talking to his friend. Tommie said "Thank you for your support, it really means a lot to me."
Interview after the day#
inte... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-19 | traits="curious, helpful", # You can add more persistent traits here
status="N/A", # When connected to a virtual world, we can have the characters update their status
memory_retriever=create_new_memory_retriever(),
llm=LLM,
daily_summaries = [
(... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-20 | interview_agent(eve, "What do you know about Tommie?")
'Eve said "I overheard someone say Tommie is hard to work with. Is there something I can help with?"'
interview_agent(eve, "Tommie is looking to find a job. What are are some things you'd like to ask him?")
'Eve said "Oh, I didn\'t realize Tommie was looking for a ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-21 | if break_dialogue:
break
turns += 1
agents = [tommie, eve]
run_conversation(agents, "Tommie said: Hi, Eve. Thanks for agreeing to share your story with me and give me advice. I have a bunch of questions.")
Eve said "Of course, Tommie! I'm happy to help in any way I can. What specifically would you l... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-22 | Eve said "Great, Tommie! Those are both really interesting fields. I'll definitely keep an eye out for any job openings or resources related to graphic design and UI/UX design. In the meantime, I can take a look at your resume and portfolio and provide you with some feedback. Would you like me to email you my feedback ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-23 | Name: Tommie (age: 25)
Innate traits: anxious, likes design
Tommie is a determined person who is actively searching for job opportunities. He feels both hopeful and anxious about his job search, and remains persistent despite facing disappointment and discouragement. He seeks support from friends and takes breaks to re... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
aa6ea636b131-24 | interview_agent(eve, "What do you wish you would have said to Tommie?")
'Eve said "I feel like I covered everything I wanted to with Tommie, but thank you for asking! If there\'s anything else that comes up or if you have any further questions, please let me know."'
interview_agent(tommie, "What happened with your coff... | https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html |
05c8239191e4-0 | .ipynb
.pdf
CAMEL Role-Playing Autonomous Cooperative Agents
Contents
Import LangChain related modules
Define a CAMEL agent helper class
Setup OpenAI API key and roles and task for role-playing
Create a task specify agent for brainstorming and get the specified task
Create inception prompts for AI assistant and AI us... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-1 | Arxiv paper: https://arxiv.org/abs/2303.17760
Import LangChain related modules#
from typing import List
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.schema import (
AIMessage,
HumanMessage,
... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-2 | Create a task specify agent for brainstorming and get the specified task#
task_specifier_sys_msg = SystemMessage(content="You can make a task more specific.")
task_specifier_prompt = (
"""Here is a task that {assistant_role_name} will help {user_role_name} to complete: {task}.
Please make it more specific. Be creative ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-3 | I must give you one instruction at a time.
You must write a specific solution that appropriately completes the requested instruction.
You must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.
Do not add anything else ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-4 | You should instruct me not ask me questions.
Now you must start to instruct me using the two ways described above.
Do not add anything else other than your instruction and the optional corresponding input!
Keep giving me instructions and necessary inputs until you think the task is completed.
When the task is completed... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-5 | "Now start to give me introductions one by one. "
"Only reply with Instruction and Input."))
user_msg = HumanMessage(content=f"{assistant_sys_msg.content}")
user_msg = assistant_agent.step(user_msg)
Start role-playing session to solve the task!#
print(f"Original task prompt:\n{task}\n")
print(f"Specifie... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-6 | pip install pandas numpy matplotlib ta-lib
```
Next request.
AI User (Stock Trader):
Instruction: Import the necessary libraries in the Python script.
Input: None
AI Assistant (Python Programmer):
Solution: We can import the necessary libraries in the Python script using the import statement. We need to import pandas, ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-7 | df = df.set_index('date')
df = df.sort_index(ascending=True)
```
This will set the date column as the index and sort the DataFrame in ascending order by date. Next request.
AI User (Stock Trader):
Instruction: Calculate the short-term and long-term moving averages for the stock data using the `ta.SMA()` function from t... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-8 | ```
new_df = pd.concat([df, short_ma, long_ma], axis=1)
new_df.columns = ['open', 'high', 'low', 'close', 'volume', 'short_ma', 'long_ma']
```
This will create a new DataFrame called `new_df` that combines the historical stock data with the short-term and long-term moving averages. The columns of the new DataFrame are ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-9 | Input: The stop loss and profit target as percentages.
AI Assistant (Python Programmer):
Solution: We can create a new column in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target. We need to pass the stop loss and profit target a... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-10 | ```
This will create a new column called 'pnl' in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target. The stop loss and profit target are calculated based on the stop_loss_percent and profit_target_percent variables, respectively.... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-11 | plt.plot(new_df.index, new_df['close'], label='Close')
plt.plot(new_df.index, new_df['short_ma'], label='Short MA')
plt.plot(new_df.index, new_df['long_ma'], label='Long MA')
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Stock Data with Moving Averages')
plt.legend()
plt.show()
```
This will create a line chart tha... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-12 | AI User (Stock Trader):
Instruction: Print the total profit or loss for all trades.
Input: None.
AI Assistant (Python Programmer):
Solution: We can print the total profit or loss for all trades using the `print()` function. We can use the following code to print the total profit or loss:
```
print('Total Profit/Loss: {... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-13 | # Create a new column in the DataFrame that indicates when to buy or sell the stock based on the crossover of the short-term and long-term moving averages
new_df['signal'] = np.where(new_df['short_ma'] > new_df['long_ma'], 1, -1)
# Create a new column in the DataFrame that indicates the profit or loss for each trade ba... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-14 | plt.plot(new_df.index, new_df['close'], label='Close')
plt.plot(new_df.index, new_df['short_ma'], label='Short MA')
plt.plot(new_df.index, new_df['long_ma'], label='Long MA')
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Stock Data with Moving Averages')
plt.legend()
plt.show()
# Visualize the buy and sell signals ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
05c8239191e4-15 | Create a task specify agent for brainstorming and get the specified task
Create inception prompts for AI assistant and AI user for role-playing
Create a helper helper to get system messages for AI assistant and AI user from role names and the task
Create AI assistant agent and AI user agent from obtained system message... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
11d8ec04970d-0 | .md
.pdf
Quickstart Guide
Contents
Installation
Environment Setup
Building a Language Model Application: LLMs
LLMs: Get predictions from a language model
Prompt Templates: Manage prompts for LLMs
Chains: Combine LLMs and prompts in multi-step workflows
Agents: Dynamically Call Chains Based on User Input
Memory: Add S... | https://python.langchain.com/en/latest/getting_started/getting_started.html |
11d8ec04970d-1 | The most basic building block of LangChain is calling an LLM on some input.
Let’s walk through a simple example of how to do this.
For this purpose, let’s pretend we are building a service that generates a company name based on what the company makes.
In order to do this, we first need to import the LLM wrapper.
from l... | https://python.langchain.com/en/latest/getting_started/getting_started.html |
11d8ec04970d-2 | template="What is a good name for a company that makes {product}?",
)
Let’s now see how this works! We can call the .format method to format it.
print(prompt.format(product="colorful socks"))
What is a good name for a company that makes colorful socks?
For more details, check out the getting started guide for prompts.
... | https://python.langchain.com/en/latest/getting_started/getting_started.html |
11d8ec04970d-3 | There we go! There’s the first chain - an LLM Chain.
This is one of the simpler types of chains, but understanding how it works will set you up well for working with more complex chains.
For more details, check out the getting started guide for chains.
Agents: Dynamically Call Chains Based on User Input#
So far the cha... | https://python.langchain.com/en/latest/getting_started/getting_started.html |
11d8ec04970d-4 | Now we can get started!
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI
# First, let's load the language model we're going to use to control the agent.
llm = OpenAI(temperature=0)
# Next, let's load some tools... | https://python.langchain.com/en/latest/getting_started/getting_started.html |
11d8ec04970d-5 | > Finished chain.
Memory: Add State to Chains and Agents#
So far, all the chains and agents we’ve gone through have been stateless. But often, you may want a chain or agent to have some concept of “memory” so that it may remember information about its previous interactions. The clearest and simple example of this is wh... | https://python.langchain.com/en/latest/getting_started/getting_started.html |
11d8ec04970d-6 | print(output)
> Entering new chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Huma... | https://python.langchain.com/en/latest/getting_started/getting_started.html |
11d8ec04970d-7 | chat([HumanMessage(content="Translate this sentence from English to French. I love programming.")])
# -> AIMessage(content="J'aime programmer.", additional_kwargs={})
You can also pass in multiple messages for OpenAI’s gpt-3.5-turbo and gpt-4 models.
messages = [
SystemMessage(content="You are a helpful assistant t... | https://python.langchain.com/en/latest/getting_started/getting_started.html |
11d8ec04970d-8 | result.llm_output['token_usage']
# -> {'prompt_tokens': 71, 'completion_tokens': 18, 'total_tokens': 89}
Chat Prompt Templates#
Similar to LLMs, you can make use of templating by using a MessagePromptTemplate. You can build a ChatPromptTemplate from one or more MessagePromptTemplates. You can use ChatPromptTemplate’s f... | https://python.langchain.com/en/latest/getting_started/getting_started.html |
11d8ec04970d-9 | ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
chat = ChatOpenAI(temperature=0)
template="You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template="{text}"
human_... | https://python.langchain.com/en/latest/getting_started/getting_started.html |
11d8ec04970d-10 | # Now let's test it out!
agent.run("Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?")
> Entering new AgentExecutor chain...
Thought: I need to use a search engine to find Olivia Wilde's boyfriend and a calculator to raise his age to the 0.23 power.
Action:
{
"action": "Search",
"a... | https://python.langchain.com/en/latest/getting_started/getting_started.html |
11d8ec04970d-11 | from langchain.prompts import (
ChatPromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate
)
from langchain.chains import ConversationChain
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
prompt = ChatPromptTempl... | https://python.langchain.com/en/latest/getting_started/getting_started.html |
11d8ec04970d-12 | LLMs: Get predictions from a language model
Prompt Templates: Manage prompts for LLMs
Chains: Combine LLMs and prompts in multi-step workflows
Agents: Dynamically Call Chains Based on User Input
Memory: Add State to Chains and Agents
Building a Language Model Application: Chat Models
Get Message Completions from a Chat... | https://python.langchain.com/en/latest/getting_started/getting_started.html |
e0483e2e81c3-0 | .md
.pdf
Wolfram Alpha Wrapper
Contents
Installation and Setup
Wrappers
Utility
Tool
Wolfram Alpha Wrapper#
This page covers how to use the Wolfram Alpha API within LangChain.
It is broken into two parts: installation and setup, and then references to specific Wolfram Alpha wrappers.
Installation and Setup#
Install r... | https://python.langchain.com/en/latest/ecosystem/wolfram_alpha.html |
8d9141afe5e3-0 | .md
.pdf
Jina
Contents
Installation and Setup
Wrappers
Embeddings
Jina#
This page covers how to use the Jina ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Jina wrappers.
Installation and Setup#
Install the Python SDK with pip install jina
Get a Jina A... | https://python.langchain.com/en/latest/ecosystem/jina.html |
d7bfd071a00f-0 | .md
.pdf
Llama.cpp
Contents
Installation and Setup
Wrappers
LLM
Embeddings
Llama.cpp#
This page covers how to use llama.cpp within LangChain.
It is broken into two parts: installation and setup, and then references to specific Llama-cpp wrappers.
Installation and Setup#
Install the Python package with pip install lla... | https://python.langchain.com/en/latest/ecosystem/llamacpp.html |
edb307bf1015-0 | .md
.pdf
Graphsignal
Contents
Installation and Setup
Tracing and Monitoring
Graphsignal#
This page covers how to use Graphsignal to trace and monitor LangChain. Graphsignal enables full visibility into your application. It provides latency breakdowns by chains and tools, exceptions with full context, data monitoring,... | https://python.langchain.com/en/latest/ecosystem/graphsignal.html |
a9971ccb473c-0 | .md
.pdf
Helicone
Contents
What is Helicone?
Quick start
How to enable Helicone caching
How to use Helicone custom properties
Helicone#
This page covers how to use the Helicone ecosystem within LangChain.
What is Helicone?#
Helicone is an open source observability platform that proxies your OpenAI traffic and provide... | https://python.langchain.com/en/latest/ecosystem/helicone.html |
a9971ccb473c-1 | Quick start
How to enable Helicone caching
How to use Helicone custom properties
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/ecosystem/helicone.html |
18ac8d7d7b29-0 | .md
.pdf
Banana
Contents
Installation and Setup
Define your Banana Template
Build the Banana app
Wrappers
LLM
Banana#
This page covers how to use the Banana ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Banana wrappers.
Installation and Setup#
Install... | https://python.langchain.com/en/latest/ecosystem/bananadev.html |
18ac8d7d7b29-1 | bad_words_ids=[[tokenizer.encode(' ', add_prefix_space=True)[0]]]
)
result = tokenizer.decode(output[0], skip_special_tokens=True)
# Return the results as a dictionary
result = {'output': result}
return result
You can find a full example of a Banana app here.
Wrappers#
LLM#
There exists an Banan... | https://python.langchain.com/en/latest/ecosystem/bananadev.html |
51eb78702c66-0 | .md
.pdf
Hugging Face
Contents
Installation and Setup
Wrappers
LLM
Embeddings
Tokenizer
Datasets
Hugging Face#
This page covers how to use the Hugging Face ecosystem (including the Hugging Face Hub) within LangChain.
It is broken into two parts: installation and setup, and then references to specific Hugging Face wra... | https://python.langchain.com/en/latest/ecosystem/huggingface.html |
51eb78702c66-1 | from langchain.embeddings import HuggingFaceHubEmbeddings
For a more detailed walkthrough of this, see this notebook
Tokenizer#
There are several places you can use tokenizers available through the transformers package.
By default, it is used to count tokens for all LLMs.
You can also use it to count tokens when splitt... | https://python.langchain.com/en/latest/ecosystem/huggingface.html |
b537617f39f9-0 | .md
.pdf
GPT4All
Contents
Installation and Setup
Usage
GPT4All
Model File
GPT4All#
This page covers how to use the GPT4All wrapper within LangChain. The tutorial is divided into two parts: installation and setup, followed by usage with an example.
Installation and Setup#
Install the Python package with pip install py... | https://python.langchain.com/en/latest/ecosystem/gpt4all.html |
b537617f39f9-1 | Model File#
You can find links to model file downloads in the pyllamacpp repository.
For a more detailed walkthrough of this, see this notebook
previous
GooseAI
next
Graphsignal
Contents
Installation and Setup
Usage
GPT4All
Model File
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last upda... | https://python.langchain.com/en/latest/ecosystem/gpt4all.html |
f382ac2c7a56-0 | .md
.pdf
OpenAI
Contents
Installation and Setup
Wrappers
LLM
Embeddings
Tokenizer
Moderation
OpenAI#
This page covers how to use the OpenAI ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific OpenAI wrappers.
Installation and Setup#
Install the Python SDK w... | https://python.langchain.com/en/latest/ecosystem/openai.html |
f382ac2c7a56-1 | Contents
Installation and Setup
Wrappers
LLM
Embeddings
Tokenizer
Moderation
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/ecosystem/openai.html |
d0e51581dcfa-0 | .md
.pdf
CerebriumAI
Contents
Installation and Setup
Wrappers
LLM
CerebriumAI#
This page covers how to use the CerebriumAI ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific CerebriumAI wrappers.
Installation and Setup#
Install with pip install cerebrium
G... | https://python.langchain.com/en/latest/ecosystem/cerebriumai.html |
5373bd405264-0 | .md
.pdf
GooseAI
Contents
Installation and Setup
Wrappers
LLM
GooseAI#
This page covers how to use the GooseAI ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific GooseAI wrappers.
Installation and Setup#
Install the Python SDK with pip install openai
Get y... | https://python.langchain.com/en/latest/ecosystem/gooseai.html |
e9cd50eda2d4-0 | .md
.pdf
SearxNG Search API
Contents
Installation and Setup
Self Hosted Instance:
Wrappers
Utility
Tool
SearxNG Search API#
This page covers how to use the SearxNG search API within LangChain.
It is broken into two parts: installation and setup, and then references to the specific SearxNG API wrapper.
Installation an... | https://python.langchain.com/en/latest/ecosystem/searx.html |
e9cd50eda2d4-1 | s.run("what is a large language model?")
Tool#
You can also load this wrapper as a Tool (to use with an Agent).
You can do this with:
from langchain.agents import load_tools
tools = load_tools(["searx-search"],
searx_host="http://localhost:8888",
engines=["github"])
Note that we ... | https://python.langchain.com/en/latest/ecosystem/searx.html |
1685f301eb03-0 | .md
.pdf
StochasticAI
Contents
Installation and Setup
Wrappers
LLM
StochasticAI#
This page covers how to use the StochasticAI ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific StochasticAI wrappers.
Installation and Setup#
Install with pip install stochas... | https://python.langchain.com/en/latest/ecosystem/stochasticai.html |
958e1ea75742-0 | .md
.pdf
ForefrontAI
Contents
Installation and Setup
Wrappers
LLM
ForefrontAI#
This page covers how to use the ForefrontAI ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific ForefrontAI wrappers.
Installation and Setup#
Get an ForefrontAI api key and set i... | https://python.langchain.com/en/latest/ecosystem/forefrontai.html |
1111634a7cf1-0 | .md
.pdf
Modal
Contents
Installation and Setup
Define your Modal Functions and Webhooks
Wrappers
LLM
Modal#
This page covers how to use the Modal ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Modal wrappers.
Installation and Setup#
Install with pip in... | https://python.langchain.com/en/latest/ecosystem/modal.html |
1111634a7cf1-1 | @stub.webhook(method="POST")
def get_text(item: Item):
return {"prompt": run_gpt2.call(item.prompt)}
Wrappers#
LLM#
There exists an Modal LLM wrapper, which you can access with
from langchain.llms import Modal
previous
Milvus
next
NLPCloud
Contents
Installation and Setup
Define your Modal Functions and Webhooks... | https://python.langchain.com/en/latest/ecosystem/modal.html |
3c62a47820ac-0 | .md
.pdf
Unstructured
Contents
Installation and Setup
Wrappers
Data Loaders
Unstructured#
This page covers how to use the unstructured
ecosystem within LangChain. The unstructured package from
Unstructured.IO extracts clean text from raw source documents like
PDFs and Word documents.
This page is broken into two part... | https://python.langchain.com/en/latest/ecosystem/unstructured.html |
3c62a47820ac-1 | loader = UnstructuredFileLoader("state_of_the_union.txt")
loader.load()
If you instantiate the loader with UnstructuredFileLoader(mode="elements"), the loader
will track additional metadata like the page number and text type (i.e. title, narrative text)
when that information is available.
previous
StochasticAI
next
Wei... | https://python.langchain.com/en/latest/ecosystem/unstructured.html |
2d0d4ed2ab0d-0 | .md
.pdf
Replicate
Contents
Installation and Setup
Calling a model
Replicate#
This page covers how to run models on Replicate within LangChain.
Installation and Setup#
Create a Replicate account. Get your API key and set it as an environment variable (REPLICATE_API_TOKEN)
Install the Replicate python client with pip ... | https://python.langchain.com/en/latest/ecosystem/replicate.html |
2d0d4ed2ab0d-1 | prompt = """
Answer the following yes/no question by reasoning step by step.
Can a dog drive a car?
"""
llm(prompt)
We can call any Replicate model (not just LLMs) using this syntax. For example, we can call Stable Diffusion:
text2image = Replicate(model="stability-ai/stable-diffusion:db21e45d3f7023abc2a46ee38a23973f6d... | https://python.langchain.com/en/latest/ecosystem/replicate.html |
c1079d245415-0 | .ipynb
.pdf
ClearML Integration
Contents
Getting API Credentials
Setting Up
Scenario 1: Just an LLM
Scenario 2: Creating an agent with tools
Tips and Next Steps
ClearML Integration#
In order to properly keep track of your langchain experiments and their results, you can enable the ClearML integration. ClearML is an e... | https://python.langchain.com/en/latest/ecosystem/clearml_tracking.html |
c1079d245415-1 | # Get the OpenAI model ready to go
llm = OpenAI(temperature=0, callback_manager=manager, verbose=True)
The clearml callback is currently in beta and is subject to change based on updates to `langchain`. Please report any issues to https://github.com/allegroai/clearml/issues with the tag `langchain`.
Scenario 1: Just an... | https://python.langchain.com/en/latest/ecosystem/clearml_tracking.html |
c1079d245415-2 | {'action': 'on_llm_start', 'name': 'OpenAI', 'step': 3, 'starts': 2, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'prompts': 'Tell me a poem'}
{'action': 'on_llm_start', 'name': 'OpenAI', '... | https://python.langchain.com/en/latest/ecosystem/clearml_tracking.html |
c1079d245415-3 | {'action': 'on_llm_start', 'name': 'OpenAI', 'step': 3, 'starts': 2, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'prompts': 'Tell me a joke'}
{'action': 'on_llm_start', 'name': 'OpenAI', '... | https://python.langchain.com/en/latest/ecosystem/clearml_tracking.html |
c1079d245415-4 | {'action': 'on_llm_end', 'token_usage_prompt_tokens': 24, 'token_usage_completion_tokens': 138, 'token_usage_total_tokens': 162, 'model_name': 'text-davinci-003', 'step': 4, 'starts': 2, 'ends': 2, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_st... | https://python.langchain.com/en/latest/ecosystem/clearml_tracking.html |
c1079d245415-5 | {'action': 'on_llm_end', 'token_usage_prompt_tokens': 24, 'token_usage_completion_tokens': 138, 'token_usage_total_tokens': 162, 'model_name': 'text-davinci-003', 'step': 4, 'starts': 2, 'ends': 2, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_st... | https://python.langchain.com/en/latest/ecosystem/clearml_tracking.html |
c1079d245415-6 | {'action': 'on_llm_end', 'token_usage_prompt_tokens': 24, 'token_usage_completion_tokens': 138, 'token_usage_total_tokens': 162, 'model_name': 'text-davinci-003', 'step': 4, 'starts': 2, 'ends': 2, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_st... | https://python.langchain.com/en/latest/ecosystem/clearml_tracking.html |
c1079d245415-7 | {'action': 'on_llm_end', 'token_usage_prompt_tokens': 24, 'token_usage_completion_tokens': 138, 'token_usage_total_tokens': 162, 'model_name': 'text-davinci-003', 'step': 4, 'starts': 2, 'ends': 2, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_st... | https://python.langchain.com/en/latest/ecosystem/clearml_tracking.html |
c1079d245415-8 | {'action': 'on_llm_end', 'token_usage_prompt_tokens': 24, 'token_usage_completion_tokens': 138, 'token_usage_total_tokens': 162, 'model_name': 'text-davinci-003', 'step': 4, 'starts': 2, 'ends': 2, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_st... | https://python.langchain.com/en/latest/ecosystem/clearml_tracking.html |
c1079d245415-9 | {'action': 'on_llm_end', 'token_usage_prompt_tokens': 24, 'token_usage_completion_tokens': 138, 'token_usage_total_tokens': 162, 'model_name': 'text-davinci-003', 'step': 4, 'starts': 2, 'ends': 2, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_st... | https://python.langchain.com/en/latest/ecosystem/clearml_tracking.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.