|
| 1 | +import argparse |
| 2 | +import logging |
| 3 | + |
| 4 | +from foundry_local import FoundryLocalManager |
| 5 | +from langchain_core.prompts import ChatPromptTemplate |
| 6 | +from langchain_openai import ChatOpenAI |
| 7 | + |
| 8 | +logger = logging.getLogger(__name__) |
| 9 | + |
| 10 | + |
| 11 | +def init_args() -> argparse.Namespace: |
| 12 | + parser = argparse.ArgumentParser( |
| 13 | + prog="foundry_local_app", |
| 14 | + description="Translate English to Japanese using Foundry Local.", |
| 15 | + ) |
| 16 | + parser.add_argument("-i", "--input", default="I love to code.") |
| 17 | + parser.add_argument("-a", "--alias", default="phi-3-mini-4k") |
| 18 | + parser.add_argument("-v", "--verbose", action="store_true") |
| 19 | + return parser.parse_args() |
| 20 | + |
| 21 | + |
| 22 | +def main( |
| 23 | + alias: str, |
| 24 | + input: str, |
| 25 | +) -> None: |
| 26 | + manager = FoundryLocalManager(alias) |
| 27 | + |
| 28 | + llm = ChatOpenAI( |
| 29 | + model=manager.get_model_info(alias).id, |
| 30 | + base_url=manager.endpoint, |
| 31 | + api_key=manager.api_key, |
| 32 | + temperature=0.0, |
| 33 | + streaming=False, |
| 34 | + ) |
| 35 | + |
| 36 | + prompt = ChatPromptTemplate.from_messages( |
| 37 | + [ |
| 38 | + ("system", "You are a helpful assistant that translates {input_language} to {output_language}."), |
| 39 | + ("human", "{input}"), |
| 40 | + ] |
| 41 | + ) |
| 42 | + |
| 43 | + chain = prompt | llm |
| 44 | + |
| 45 | + try: |
| 46 | + ai_msg = chain.invoke( |
| 47 | + { |
| 48 | + "input_language": "English", |
| 49 | + "output_language": "Japanese", |
| 50 | + "input": input, |
| 51 | + }, |
| 52 | + ) |
| 53 | + logger.debug(f"AI message: {ai_msg}") |
| 54 | + print(f"Response: {ai_msg.content}") |
| 55 | + except Exception as e: |
| 56 | + logger.error(e) |
| 57 | + raise e |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + """ |
| 62 | + # Usage |
| 63 | + $ uv run python apps/1_call_azure_openai_chat/foundry_local_app.py --help |
| 64 | + # Example |
| 65 | + $ uv run python apps/1_call_azure_openai_chat/foundry_local_app.py --verbose |
| 66 | + # References |
| 67 | + - Get started with Foundry Local: https://learn.microsoft.com/azure/ai-foundry/foundry-local/get-started |
| 68 | + - Build a translation application with LangChain: https://learn.microsoft.com/azure/ai-foundry/foundry-local/how-to/how-to-use-langchain-with-foundry-local?pivots=programming-language-python |
| 69 | + """ |
| 70 | + args = init_args() |
| 71 | + |
| 72 | + if args.verbose: |
| 73 | + logging.basicConfig(level=logging.DEBUG) |
| 74 | + |
| 75 | + main( |
| 76 | + alias=args.alias, |
| 77 | + input=args.input, |
| 78 | + ) |
0 commit comments