Replies: 1 comment
-
Yes, you can show a table as an output through OpenAI APIs by defining a custom output schema using Pydantic. Here is an example of how you can achieve this: from typing import List
from pydantic import BaseModel, Field
from langchain.chains.openai_functions import create_qa_with_structure_chain
from langchain.prompts.chat import ChatPromptTemplate, HumanMessagePromptTemplate
from langchain_core.messages import HumanMessage, SystemMessage
class TableResponseSchema(BaseModel):
"""A table response schema."""
headers: List[str] = Field(..., description="Headers of the table")
rows: List[List[str]] = Field(..., description="Rows of the table")
prompt_messages = [
SystemMessage(
content=(
"You are a world class algorithm to answer "
"questions in a specific format."
)
),
HumanMessage(content="Answer question using the following context"),
HumanMessagePromptTemplate.from_template("{context}"),
HumanMessagePromptTemplate.from_template("Question: {question}"),
HumanMessage(
content="Tips: Make sure to answer in the correct format. Return the table with headers and rows."
),
]
chain_prompt = ChatPromptTemplate(messages=prompt_messages)
qa_chain_pydantic = create_qa_with_structure_chain(
llm, TableResponseSchema, output_parser="pydantic", prompt=chain_prompt
)
final_qa_chain_pydantic = StuffDocumentsChain(
llm_chain=qa_chain_pydantic,
document_variable_name="context",
document_prompt=doc_prompt,
)
retrieval_qa_pydantic = RetrievalQA(
retriever=docsearch.as_retriever(), combine_documents_chain=final_qa_chain_pydantic
)
query = "What did he say about russia"
result = retrieval_qa_pydantic.run(query) This code sets up a custom response schema for a table with headers and rows, and configures the OpenAI API to return responses in this format [1]. Additionally, you can use LangChain to interact with CSV data and generate tables. Here is an example of how you can use LangChain with Pandas to generate a table: import pandas as pd
from langchain_experimental.tools import PythonAstREPLTool
df = pd.read_csv("titanic.csv")
tool = PythonAstREPLTool(locals={"df": df})
tool.invoke("df.head().to_markdown()") This approach allows you to load a CSV file as a dataframe and use a Python-executing tool to generate a table [2]. For more advanced use cases, you can create a chain or an agent to interact with the data and generate tables based on user queries. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Checked other resources
Commit to Help
Example Code
Description
is there any way to show a table as an output through open ai api's?
ans = new_project_qa.invoke(query)
try:
ans_output = ans["answer"]
except:
ans_output = ans["result"]
System Info
langchain
ubuntu
Beta Was this translation helpful? Give feedback.
All reactions